- Home /
Scripting object movement?
Hello, I am developing a 2D shooter and I have some questions regarding the scripting. I am able to understand the basic logic and process of what needs to be done:
when the mouse is clicked, I want to make the bullet object move outward from the player in the direction of the mouse cursor (and If the mouse it held down, it would be rapid fire), how would this be done? The game is along the ZX plane if that helps.
Answer by IJM · Nov 12, 2010 at 10:12 PM
Hello.
First of all you need to rotate your player towards the mouse, and to do that you will need to use transform.LookAt(...) function.
To get the point on wich your player will look at you will need to use Camera. ScreenToWorldPoint since the pointer "lives" in 2D space,and your player is in the 3D space.
Input.GetMouseButton(...) will let you know whether the mouse button is held down, and you can use Time.time to determine for how long it is down. Also you have Input.GetMouseButtonDown(...) wich will tell you whether the mouse button was pressed in the current frame, and you can use that for the first shot.
Direction of the bullet will be playerGameObject.transform.forward, and to move it you will just need to do something like:
bulletGameObject.transform.position += bulletGameObject.transform.forward * Speed;
To create a new GameObject from the script you will need to use (in C#):
GameObject MyGameObject = new GameObject();
And to add any script (or other component like mesh), you will need to use:
MyGameObject.AddComponent(ComponentName);//or ScriptName
To learn how to use this functions go to Unity's Scirpt Reference page:
http://unity3d.com/support/documentation/ScriptReference/
p.s. Just to let you know, no one will write the code for you ;)
Your answer
