- Home /
How to make an object move towards an object at a constant pace, no matter how fast the object is?
Hello, I am trying to make a little gun kind of thing where wherever I click the bullet aims in that direction, with my code I have got the object to move in the direction and face the direction. However, my problem is that if the click is far away the object moves very fast and when I click close it moves incredibly slowly, I know this is because I am timesing the area of the click. But I can't think of a way I can do it differently.
var mousePosition : Vector3;
function Start () {
var speed : int = 40;
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
var dir : Vector3 = (mousePosition - transform.position).normalized * speed;
var point: Vector3 = mousePosition;
point.z = 0.0;
transform.LookAt(point);
transform.rotation.x = 0;
transform.rotation.y = 0;
GetComponent.<Rigidbody2D>().velocity = dir;
}
Thanks a lot, Ellis
you could consider using Vector3.$$anonymous$$oveTowards unless you absolutely need to use rigidbodies:
https://docs.unity3d.com/ScriptReference/Vector3.$$anonymous$$oveTowards.html
in which case maybe use Rigidbody2D.$$anonymous$$ovePosition:
https://docs.unity3d.com/ScriptReference/Rigidbody.$$anonymous$$ovePosition.html
hope that helps.
remove velocity = dir line
and don't forget to add Time.deltaTime to any speed multiplier parameter, always.Since you want that bullet to fly realtime speed, not phone processor's
var dir : Vector3 = (mousePosition - transform.position).normalized * speed*Time.deltaTime;