Move player use Input.getKeyDown unity - unity3d

Hello guys i want move player between two position use Input.getKeyDown
firstPosition = new vector2(0,0); secondPosition = new vector2(0,5);
if player in firstPosition will go to secondPosition if player press E key
if player in secondPosition will go to firstPosition if player press E key
(movement method is transform.Translate)
my code
if (stairsOn)
{
inHelecopter.inHelecopter = true;
rig2d.simulated = !enabled;
if (transform.localPosition.y > stairS.maxHigh)//down
{
dirUp = false;
}
else if (transform.localPosition.y <= stairS.minHigh)
{//up
dirUp = true;
}
if (transform.localPosition.y >= stairS.maxHigh || transform.localPosition.y <= stairS.minHigh)
{
rig2d.simulated = enabled;
stairsOn = false;
}
if (dirUp)
{
transform.Translate(Vector3.up * 2 * Time.fixedDeltaTime, Space.Self);
}
else
{
transform.Translate(Vector3.down * 2 * Time.fixedDeltaTime, Space.Self);
}
}

Try this:
bool b = true;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (b)
{
transform.Translate(secondPosition - firstPosition);
b = false;
}
else
{
transform.Translate(firstPosition - secondPosition);
b = true;
}
}
}
In practice, I assign a variable that controls whether it is in the first or second position and moves the player towards the other.
In this script I use the transform.Translate method, but if you can I recommend that you simply assign the position like this:
bool b = true;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (b)
{
transform.position = secondPosition;
b = false;
}
else
{
transform.position = firstPosition;
b = true;
}
}
}
Good work!

Related

How can I connect button to function?

we have a dash button in the game. If we press the button dash button is working well but the problem is if we press anywhere on screen it is working too! We only want to work that function with button.
Anyone help us please?
Code:
public void Dash()
{
if (Input.GetMouseButtonDown(0))
{
activeMoveSpeed = dashSpeed;
dashCounter = dashLength;
}
if (dashCounter > 0)
{
canShoot = false;
dashCounter -= Time.deltaTime;
if (dashCounter <= 0)
{
canShoot = false;
activeMoveSpeed = speed;
dashCoolCounter = dashCoolDown;
}
}
if (dashCoolCounter > 0)
{
canShoot = false;
dashCoolCounter -= Time.deltaTime;
}
}
private void FixedUpdate()
{
Movement();
Dash();
}
Button and Game
Button
The function you specify in OnClick will be called whenever the button is clicked.
Currently, you are not using the button at all. I think you meant something like this (StartDash() is the function that should be chosen in OnClick):
public void StartDash()
{
activeMoveSpeed = dashSpeed;
dashCounter = dashLength;
}
private void DoDash()
{
if (dashCounter > 0)
{
canShoot = false;
dashCounter -= Time.deltaTime;
if (dashCounter <= 0)
{
canShoot = false;
activeMoveSpeed = speed;
dashCoolCounter = dashCoolDown;
}
}
if (dashCoolCounter > 0)
{
canShoot = false;
dashCoolCounter -= Time.deltaTime;
}
}
private void FixedUpdate()
{
Movement();
DoDash();
}
Take a look at the related pages in the Unity Documentation:
Manual - Button
Scripting - UI.Button
Scripting - UI.Button.onclick

Unity C# transform.LookAt rotating on wrong axis

Im making the basic foundations of an RPG game. Its point and click, using a navmesh. I have set up the player to move to an enemy and attack when in range. The problem i am having is that when the player reaches the enemy (or the chest/interactable) it rotates on the x axis. Im assuming its something to do with the lookAt function using the pivot point of the target object, but i cannot find a solution. Any help directing me to a solution would be amazing. I have scoured sites, forums and the Unity API for a couple of days now. Im sure its something simple, i just cant seem to see it.
Much love
public class clickToMove : MonoBehaviour
{
// Attack variables
[Header("Attack")]
public float attackDistance;
public float attackRate;
private float nextAttack;
//Navigation variables
private NavMeshAgent navMeshAgent;
//private bool walking;
//Animation variables
private Animator anim;
//Enemy variables
private Transform targetedEnemy;
private bool enemyClicked;
//Interactable variables
private Transform targetedObject;
private bool objectClicked;
void Awake()
{
anim = GetComponent<Animator>();
navMeshAgent = GetComponent<NavMeshAgent>();
}
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Input.GetButton("Fire1"))
{
navMeshAgent.ResetPath();
if(Physics.Raycast(ray, out hit, 1000))
{
if(hit.collider.tag == "Enemy")
{
enemyClicked = true;
targetedEnemy = hit.transform;
}
else if (hit.collider.tag == "Chest")
{
objectClicked = true;
targetedObject = hit.transform;
}
else if(hit.collider.tag == "Player")
{
//walking = false;
navMeshAgent.isStopped = true;
}
else
{
//walking = true;
enemyClicked = false;
navMeshAgent.isStopped = false;
navMeshAgent.destination = hit.point;
}
}
}
if (enemyClicked)
{
MoveAndAttack();
}
else if(objectClicked && targetedObject.gameObject.tag == "Chest")
{
Interaction(targetedObject);
}
else
{
if (!navMeshAgent.pathPending && navMeshAgent.remainingDistance <= navMeshAgent.stoppingDistance)
{
//walking = false;
}
else if (!navMeshAgent.pathPending && navMeshAgent.remainingDistance >= navMeshAgent.stoppingDistance)
{
//walking = true;
}
}
//anim.SetBool("isWalking", walking);
//TODO: needs finishing. Still need to lock it to the y axis to stop its rotation being funny.
if (Input.GetKey(KeyCode.LeftShift))
{
//walking = false;
navMeshAgent.isStopped = true;
transform.LookAt(ray.origin + ray.direction * ((transform.position - Camera.main.transform.position).magnitude * 0.5f));
}
}
// TODO: still a bug where the player rotates 15 deg on x axis when it reaches target. Has something to do with the Lookat function.
void MoveAndAttack()
{
if (targetedEnemy == null)
{
return;
}
navMeshAgent.destination = targetedEnemy.position;
if (!navMeshAgent.pathPending && navMeshAgent.remainingDistance >= attackDistance)
{
navMeshAgent.isStopped = false;
//walking = true;
}
else if (!navMeshAgent.pathPending && navMeshAgent.remainingDistance <= attackDistance)
{
//anim.SetBool("isAttacking", false);
transform.LookAt(targetedEnemy);
Vector3 dirToAttack = targetedEnemy.transform.position - transform.position;
if(Time.time > nextAttack)
{
nextAttack = Time.time + attackRate;
//anim.SetBool("isAttacking", true);
}
navMeshAgent.isStopped = true;
//walking = false;
}
}
void Interaction(Transform target)
{
// set target
navMeshAgent.destination = target.position;
//go close to the target
if(!navMeshAgent.pathPending && navMeshAgent.remainingDistance > attackDistance)
{
navMeshAgent.isStopped = false;
//walking = true;
}
//read the info
else if (!navMeshAgent.pathPending && navMeshAgent.remainingDistance <= attackDistance)
{
navMeshAgent.isStopped = true;
transform.LookAt(targetedObject);
//walking = false;
//play animation
//target.gameObject.getComponentInChildren<Animator>().SetTrigger("Open");
objectClicked = false;
navMeshAgent.ResetPath();
}
}
}

Rigidbody character controller

I'm working on a character controller, everything works fine except two things and I can't find a way to solve this :(
This is the code of my controller script :
using UnityEngine;
public class ControlsManager : MonoBehaviour
{
public Transform playerBody;
private Rigidbody _rigidbody;
private Transform _playerCamera;
private Vector2 _mousePosition;
private Vector2 _precMousePosition;
private float _rJoystickX;
private float _rJoystickY;
private float _sprint;
private bool _jump;
private Vector3 _bodyTranslation;
private bool _bodyTranslationChange;
private Vector3 _bodyRotation;
private bool _bodyRotationChange;
private Vector3 _cameraRotation;
private bool _cameraRotationChange;
private void Awake()
{
_rigidbody = playerBody.GetComponent<Rigidbody>();
_playerCamera = Utilities.mainCamera.transform;
_mousePosition = Input.mousePosition;
}
private void Update()
{
_sprint = 1;
// Cursor lock for camera rotation
if (Input.GetKeyDown(Utilities.controls.lockCursorMouse))
{
if (Cursor.lockState == CursorLockMode.None)
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
else
{
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
}
}
if (!Utilities.isGamePaused)
{
if (Input.GetJoystickNames().Length > 0 && Input.GetJoystickNames()[0] != "")
{
// Camera rotation for controller
_rJoystickX = Input.GetAxis("RJoystickX");
_rJoystickY = Input.GetAxis("RJoystickY");
if (_rJoystickX != 0) {
_bodyRotation.y += Utilities.controls.controllerSens * _rJoystickX * Time.deltaTime;
_bodyRotationChange = true;
}
if (_rJoystickY != 0)
{
_cameraRotation.x += Utilities.controls.controllerSens * _rJoystickY * Time.deltaTime;
_cameraRotationChange = true;
}
// Movements for controller
if(Input.GetKey(Utilities.controls.sprintController))
{
_sprint = 1.6f;
}
if (Input.GetAxis("LJoystickY") > 0)
{
_bodyTranslation += playerBody.forward * _sprint * Time.deltaTime;
_bodyTranslationChange = true;
}
if (Input.GetAxis("LJoystickY") < 0)
{
_bodyTranslation -= playerBody.forward * Time.deltaTime;
_bodyTranslationChange = true;
}
if (Input.GetAxis("LJoystickX") < 0)
{
_bodyTranslation -= playerBody.right * Time.deltaTime;
_bodyTranslationChange = true;
}
if (Input.GetAxis("LJoystickX") > 0)
{
_bodyTranslation += playerBody.right * Time.deltaTime;
_bodyTranslationChange = true;
}
}
if (Cursor.lockState == CursorLockMode.Locked)
{
// Camera rotation for mouse
_precMousePosition = _mousePosition;
_mousePosition.x = Input.GetAxis("Mouse X");
_mousePosition.y = Input.GetAxis("Mouse Y");
if (_mousePosition.x != _precMousePosition.x)
{
_bodyRotation.y += _mousePosition.x * Utilities.controls.mouseSens;
_bodyRotationChange = true;
}
if (_mousePosition.y != _precMousePosition.y)
{
_cameraRotation.x += -_mousePosition.y * Utilities.controls.mouseSens;
_cameraRotationChange = true;
}
// Movements for mouse
_sprint = 1;
if(Input.GetKey(KeyCode.LeftShift))
{
_sprint = 1.6f;
}
if (Input.GetKeyDown(KeyCode.Space))
{
_jump = true;
}
if (Input.GetKey(Utilities.controls.forward))
{
_bodyTranslation += playerBody.forward * (_sprint * Time.deltaTime);
_bodyTranslationChange = true;
}
if (Input.GetKey(Utilities.controls.backward))
{
_bodyTranslation -= playerBody.forward * Time.deltaTime;
_bodyTranslationChange = true;
}
if (Input.GetKey(Utilities.controls.left))
{
_bodyTranslation -= playerBody.right * Time.deltaTime;
_bodyTranslationChange = true;
}
if (Input.GetKey(Utilities.controls.right))
{
_bodyTranslation += playerBody.right * Time.deltaTime;
_bodyTranslationChange = true;
}
///////////////////////////////// Debug
if (Input.GetKey(KeyCode.DownArrow))
{
_bodyTranslation -= playerBody.up * Time.deltaTime;
_bodyTranslationChange = true;
}
if (Input.GetKey(KeyCode.UpArrow))
{
_bodyTranslation += playerBody.up * Time.deltaTime;
_bodyTranslationChange = true;
}
}
}
// Rotations
if (_bodyRotationChange)
{
playerBody.localRotation *= Quaternion.Euler(_bodyRotation);
}
_bodyRotationChange = false;
_bodyRotation = Vector3.zero;
if (_cameraRotationChange)
{
_playerCamera.localRotation *= Quaternion.Euler(_cameraRotation);
}
_cameraRotationChange = false;
_cameraRotation = Vector3.zero;
if (Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
}
private void FixedUpdate()
{
if (_bodyTranslationChange)
{
_rigidbody.AddForce(_bodyTranslation * Utilities.controls.playerSpeed, ForceMode.VelocityChange);
}
if (_jump)
{
_jump = false;
_rigidbody.AddForce(playerBody.up * 500, ForceMode.Impulse);
}
_rigidbody.drag = playerBody.position.y > -0.6f ? 1 : 8;
_bodyTranslationChange = false;
_bodyTranslation = Vector3.zero;
}
}
The main two problems are :
As I do rotations in Update, and movements in FixedUpdates, there is some annoying jitter when I both move and rotate at the same time. I tried to show this in a gif but everything seems laggy so I can't really show it.
As I use AddForce() to move my character, I had to increase the drag of my rigidbody (up to 8) si it doesn't "slide" when you stop moving. This works great but now I can't jump properly because of that. I found a workaround, by putting the drag back to 1 when I'm in the air, but then if I jump and move, I move 8x faster in the air which is annoying aswell.
Am I doing thinks completely wrong ? I first did not use AddForce but normal vector translations to move the character, but collisions were buggy as hell, I could go through most walls, objects... etc
Thanks if you read all that !
when working with Pyhsics (RB) NEVER change the transform directly and never ever to this in Update! all changes have to be made inside FixedUpdate!
playerBody.localRotation *= Quaternion.Euler(_bodyRotation); <-- in Update.
Also use Rigidbody.MoveRotation instead of directy change values.
This happens because of pyhsics will work in a different update process and when you change Values within this process unity gets confused and you break the physics -> Jitter
Ok, after hours of trying to make something smooth with Rigidbody, I can't get anything perfect.
I'll just use a basic Character controller and handle collisions myself.
Thanks anyway !

Player want to move left and right from single - touch (Unity)

I made the game in Unity Space Shooter. In my Space shooter there is 2 button it work for Left and Right moving. I want when we touch the left button player go to left only in Single Touch same like Right Button also.
This , are the some codes which i used in Game. Please Help me out from this.
TouchControl.cs
using UnityEngine;
using System.Collections;
public class TouchControl : MonoBehaviour {
public GUITexture moveLeft;
public GUITexture moveRight;
public GUITexture fire;
public GameObject player;
private PlayerMovement playerMove;
private Weapon[] weapons;
void Start()
{
playerMove = player.GetComponent<PlayerMovement> ();
}
void CallFire()
{
weapons = player.GetComponentsInChildren<Weapon> ();
foreach (Weapon weapon in weapons) {
if(weapon.enabled == true)
weapon.Fire();
}
}
void Update()
{
// int i = 0;
if(Input.touchCount > 0)
{
for(int i =0; i < Input.touchCount; i++)
{
// if(moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
// {
// if(Input.touchCount > 0)
// {
// playerMove.MoveLeft();
// }
// }
// if(moveRight.HitTest(Input.GetTouch(i).position, Camera.main))
// {
// if(Input.touchCount > 0)
// {
// playerMove.MoveRight();
// }
// }
// if(moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
// {
// if(Input.touchCount > 0)
// {
// CallFire();
// }
// }
// Touch t = Input.GetTouch(i);
Touch t = Input.GetTouch (i);
Input.multiTouchEnabled = true;
if(t.phase == TouchPhase.Began || t.phase == TouchPhase.Stationary)
{
if(moveLeft.HitTest(t.position, Camera.main))
{
playerMove.MoveLeft ();
}
if(moveRight.HitTest(t.position, Camera.main))
{
playerMove.MoveRight();
}
}
if(t.phase == TouchPhase.Began)
{
if(fire.HitTest(t.position, Camera.main))
{
CallFire();
}
}
if(t.phase == TouchPhase.Ended)
{
}
}
}
}
}
PlayerMovement.cs
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public float speedMove = 6.0f;
public float bonusTime;
private bool toLeft = false;
private bool toRight = false;
public GameObject shield;
public GUIText bonustimeText;
private bool counting = false;
private float counter;
private Weapon[] addWeapons;
public Sprite strongShip;
public Sprite normalSprite;
public Sprite shieldSprite;
private SpriteRenderer sRender;
private Weapon weaponScript;
void Start () {
counter = bonusTime;
sRender = GetComponent<SpriteRenderer> ();
addWeapons = GetComponentsInChildren<Weapon> ();
foreach (Weapon addWeapon in addWeapons) {
addWeapon.enabled = false;
}
weaponScript = GetComponent<Weapon>();
weaponScript.enabled = true;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.A)) {
toLeft = true;
}
if (Input.GetKeyUp (KeyCode.A)) {
toLeft = false;
}
if (Input.GetKeyDown (KeyCode.D)) {
toRight = true;
}
if (Input.GetKeyUp (KeyCode.D)) {
toRight = false;
}
if (counting) {
counter -= Time.deltaTime;
bonustimeText.text = counter.ToString("#0.0");
}
}
void FixedUpdate()
{
if (toLeft) {
MoveLeft();
}
if (toRight) {
MoveRight();
}
}
public void MoveLeft()
{
transform.Translate(Vector2.right * -speedMove* Time.deltaTime);
}
public void MoveRight()
{
transform.Translate(Vector2.right * speedMove * Time.deltaTime);
}
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "StrongMode") {
Destroy (coll.gameObject);
counting = true;
StrongMode();
Invoke ("Downgrade", bonusTime);
}
if (coll.gameObject.tag == "ShieldMode") {
Destroy (coll.gameObject);
counting = true;
ShieldMode();
Invoke("Downgrade", bonusTime);
}
if (coll.gameObject.tag == "Life") {
GUIHealth gui = GameObject.Find ("GUI").GetComponent<GUIHealth> ();
gui.AddHealth();
SendMessage("AddHp");
SoundHelper.instanceSound.PickUpSound();
Destroy(coll.gameObject);
}
if (coll.gameObject.tag == "Enemy") {
SendMessage("Dead");
}
}
void Downgrade()
{
SoundHelper.instanceSound.BonusDownSound ();
counting = false;
bonustimeText.text = "";
counter = bonusTime;
sRender.sprite = normalSprite;
weaponScript.enabled = true;
foreach (Weapon addWeapon in addWeapons) {
addWeapon.enabled = false;
}
weaponScript.enabled = true;
shield.SetActive (false);
}
void StrongMode()
{
SoundHelper.instanceSound.BonusUpSound ();
sRender.sprite = strongShip;
foreach (Weapon addWeapon in addWeapons) {
addWeapon.enabled = true;
}
weaponScript.enabled = false;
}
void ShieldMode()
{
SoundHelper.instanceSound.BonusUpSound ();
sRender.sprite = shieldSprite;
shield.SetActive (true);
}
// void OnDestroy()
// {
// bonustimeText.text = "";
// }
}
In the Player Controller script Create:
public Vector3 playerDirection = Vector3.zero;
Then in touch control instead of:
if (moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.MoveLeft();
}
}
if (moveRight.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.MoveRight();
}
}
Use:
if (moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.playerDirection = Vector3.left;
}
}
if (moveRight.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.playerDirection = Vector3.right;
}
}
Then in the Update method of Player Controller use:
transform.Translate(playerDirection * speedMove * Time.deltaTime);
public class PlayerController {
public EPlayerState playerState = EPLayerState.Idle;
void Update () {
// If click right button
playerState = EPlayerState.MoveRight;
// Else if click left button
playerState = EPlayerState.MoveLeft
if (playerState == EPlayerState.MoveRight)
// Move player right;
if (playerState == EPlayerState.MoveLeft
// Move player right;
}
}
public enum EPlayerState {
Idle,
MoveRight,
MoveLeft
}
You can also use something like a boolean called isRight, move right when it's true and left when it's false. Then when you click left or right button just change the variable.
`using UnityEngine;
public class HalfScreenTouchMovement : MonoBehaviour
{
private float screenCenterX;
private void Start()
{
// save the horizontal center of the screen
screenCenterX = Screen.width * 0.5f;
}
private void Update()
{
// if there are any touches currently
if(Input.touchCount > 0)
{
// get the first one
Touch firstTouch = Input.GetTouch(0);
// if it began this frame
if(firstTouch.phase == TouchPhase.Began)
{
if(firstTouch.position.x > screenCenterX)
{
// if the touch position is to the right of center
// move right
}
else if(firstTouch.position.x < screenCenterX)
{
// if the touch position is to the left of center
// move left
}
}
}
}
}`
May be helpfull
create script. for example player.cs
public class PlayerController : MonoBehaviour
{
bool swipeRight = false;
bool swipeLeft = false;
bool touchBlock = true;
bool canTouchRight = true;
bool canTouchLeft = true;
void Update()
{
swipeLeft = Input.GetKeyDown("a") || Input.GetKeyDown(KeyCode.LeftArrow);
swipeRight = Input.GetKeyDown("d") || Input.GetKeyDown(KeyCode.RightArrow);
TouchControl();
if(swipeRight) //rightMove logic
else if(swipeLeft) //leftMove logic
}
void TouchControl()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved && touchBlock == true)
{
touchBlock = false;
// Get movement of the finger since last frame
var touchDeltaPosition = Input.GetTouch(0).deltaPosition;
Debug.Log("touchDeltaPosition "+touchDeltaPosition);
if(touchDeltaPosition.x > 0 && canTouchRight == true)
{
//rightMove
swipeRight = true; canTouchRight = false;
Invoke("DisableSwipeRight",0.2f);
}
else if(touchDeltaPosition.x < 0 && canTouchLeft == true)
{
//leftMove
swipeLeft = true; canTouchLeft = false;
Invoke("DisableSwipeLeft",0.2f);
}
}
}
void DisableSwipeLeft()
{
swipeLeft = false;
touchBlock = true;
canTouchLeft = true;
}
void DisableSwipeRight()
{
swipeRight = false;
touchBlock = true;
canTouchRight = true;
}
}

Drag and drop in unity 2d

I am trying to implement drag and drop functionality for my game in unity 2d. I have multiple copies of same object in my screen and they differ only by collider name. I attached the same script to them. Here is a piece of my code
function Start () {
playerTouches = [-1, -1];
}
function resetPlayer(touchNumber: int) {
for(var i = 0; i < playerTouches.length; ++i) {
if(touchNumber == playerTouches[i]) {
playerTouches[i] = -1;
}
}
}
function getCollider(vec: Vector2) {
var ray : Ray = Camera.main.ScreenPointToRay(vec);
var hit : RaycastHit2D = Physics2D.Raycast(ray.origin, ray.direction);
if (hit) {
if (hit.collider != null) {
Debug.Log(hit.collider.name);
return hit.collider.name;
} else {
Debug.Log("is null");
return "null";
}
} else {
Debug.Log("empty");
return "";
}
return "";
}
function processTouch(touch: Touch, touchNumber: int) {
if(touch.phase == TouchPhase.Began) {
var colliderName: String = getCollider(touch.position);
if(colliderName == "Object01" && playerTouches[0] == -1) {
playerTouches[0] = touchNumber;
} else if(colliderName == "Object02" && playerTouches[1] == -1) {
playerTouches[1] = touchNumber;
}
} else if(touch.phase == TouchPhase.Moved) {
// get object and change coords
} else if(touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled) {
resetPlayer(touchNumber);
}
}
function Update() {
if(Input.touchCount > 0) {
//Debug.Log("count = " + Input.touchCount);
for(var i = 0; i < Input.touchCount; i++)
{
processTouch(Input.GetTouch(i), i);
//Debug.Log("touch : " + i + " " + Input.GetTouch(i).position);
}
}
}
For now I'm detecting on which object user touch. I need to be able to get that object and change it's position.
I also found this code snippet which allows to move rigidbody
var touchDeltaPosition: Vector2 = touch.deltaPosition;
var touchPosition: Vector2;
touchPosition.Set(touchDeltaPosition.x, touchDeltaPosition.y);
rigidbody2D.transform.position = Vector2.Lerp(transform.position, touchPosition, Time.deltaTime * spd);
but it moves all objects regardless of what object I select.
Well, you can do like this. If you have 12 copies of same object and want to move the object which selected by user. So when user Touches the object Change that GameObject tag or Name to another tag. Afterward you can use the some Conditional Statement to work with your code.
Example :
if(Input.GetMouseButtonDown(0)) {
Debug.Log("Mouse is down");
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo = new RaycastHit();
//bool hit = Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hitInfo);
if(Physics.Raycast(ray, out hitInfo, 30)) {
Debug.Log("Hit " + hitInfo.transform.gameObject.name);
if(hitInfo.transform.gameObject.tag == "Deselected") {
//Debug.Log ("It's working! Attaching MoveCube Script to game :" + hitInfo.transform.gameObject.tag);
findObject = GameObject.FindGameObjectsWithTag("Deselected");
foreach(GameObject go in findObject) {
//go.gameObject.renderer.material.color = Color.white;
go.GetComponent<MoveCube>().enabled = false;
if(hitInfo.transform.gameObject.name.Equals(go.gameObject.name)) {
//hitInfo.transform.renderer.material.color = Color.white;
hitInfo.transform.gameObject.GetComponent<MoveCube>().enabled = true;
changeTAG = true;
} else {
hitInfo.transform.gameObject.tag = "Deselected"
}
}
playerObject = GameObject.FindGameObjectsWithTag("Player");
foreach(GameObject game in playerObject) {
count++;
if(count == 1) {
hitInfo.transform.gameObject.tag = "Player";
}
if(count >= 1) {
game.gameObject.tag = "Deselected";
game.gameObject.GetComponent<MoveCube>().enabled = false;
//game.gameObject.renderer.material.color = Color.white;
}
}
if(changeTAG) {
hitInfo.transform.gameObject.tag = "Player";
/*if (hitInfo.transform.gameObject.GetComponent<Rigidbody> ()) {
Debug.Log ("RigidBody is already added Can't add another RigidBody");
hitInfo.transform.rigidbody.WakeUp ();
} else {
hitInfo.transform.gameObject.AddComponent<Rigidbody> ().useGravity = false;
// hitInfo.transform.gameObject.GetComponent<Rigidbody> ().WakeUp ();
}*/
changeTAG = false;
} else if(!changeTAG) {
hitInfo.transform.gameObject.tag = "Deselected";
}
} else {
Debug.Log("Not Working");
}
} else {
Debug.Log("No hit");
}
Debug.Log("Mouse is down");
}
The above code is for Change the tag for selected and deselected cube. After that you can easily identify the Selected gameObject and can move it where ever you want.
You can use this code in the Update function.