- Home /
Move an object from point A to B?
Hello, when I click the mouse, I want to move an object outwards from point A in the direction of point B at a set velocity. The game is 2D (along the ZX plane) with an over head camera, and I want point B to be wherever the mouse is clicked on the screen, how can that be done.
I have tried this;
var projectile : Rigidbody; var speed = 2; function Update() { if( Input.GetButtonDown( "Fire1" ) )
{ var instantiatedProjectile : Rigidbody = Instantiate( projectile, transform.position, transform.rotation );
instantiatedProjectile.velocity = transform.TransformDirection (Event.mousePosition); }
}
But using this just makes the object move in a weird direction (sometimes even at the camera) I have also tried to work in "Input.mousePosition" but I cannot get that to work. Thank you.
Answer by Adam Rademacher · Nov 14, 2010 at 05:39 AM
You need to translate from screen to world space somehow. You can do this by Camera.ScreenToWorldPoint and raycasting to hit a collider as in the fourth and fifth examples here
Thank you for your help, but I am a little bit lost. I added the first script to the scenes camera and I am able to see the point that it is referencing. But have tried adding one of the second scripts you linked to me and nothing noticeable happens (I have tried adding it to both the player and the camera objects), and how would I incorporate the original script I posted?)
What I would probably do is throw a transform.LookAt(Camera.ScreenToWorldPoint(Input.mousePosition)); in between instantiate and velocity. Then I'd set velocity = transform.forward * speed;