0
votes

Good day, I want to move my Rigidbody2D object forward at constant speed and change it direction when user click on screen. I have code:

public float speed;

void FixedUpdate() 
{
    if(platform == RuntimePlatform.Android || platform == RuntimePlatform.IPhonePlayer){
        if(Input.touchCount > 0) {
            if(Input.GetTouch(0).phase == TouchPhase.Began){

            }
        }
    } else {
        if(Input.GetMouseButtonDown(0)) {
            var touchPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
            Quaternion rot = Quaternion.LookRotation (transform.position - touchPosition, Vector3.forward);
            transform.rotation = rot;
            transform.eulerAngles = new Vector3 (0, 0, transform.eulerAngles.z); // only z rotation
            myScriptRigidBody.velocity = (touchPosition - transform.position).normalized * speed;
        }
    }
}

As I understand, the object should change it's direction to mouse click position and move at constant speed. But on practise the object's speed depends on how far from current object position user clicked on screen. It is strange, bcs I normalized my direction vector and "speed" var is constant. What am I doing wrong? Thx.

3
When you say "the object's speed depends on how far from current object position user clicked on screen", how exactly does the speed depend on the position? - 31eee384

3 Answers

2
votes

You could try Vector3.MoveTowards, and use your last mouse click as the position the object should move to :-)

1
votes

The problem is that the z component of the vector returned by ScreenToWorldPoint is the camera z position. You only need the x and y components.

var touchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
touchPosition = new Vector3(touchPosition.x,touchPosition.y,0);
1
votes

The idea is that when you click somewhere, the object will rotate, which you already did. But the velocity should not depend on where you clicked.

So, the velocity is just the same. Don't change it.

myScriptRigidBody.velocity = speed;

And this should work just fine.