- Home /
How to make a box follow the cursor
Hello!
I am making a 2D game. How can I make the box to follow the cursor? so when I move the cursor to a direction, the box will stay under the cursor.
Thanks!
What is a "box" to you? A game object with a box mesh, or a gui/sprite box in 2d?
Answer by Meater6 · Mar 13, 2011 at 07:25 PM
You can create a ray from the mouse to your 2d/3d world. Then make the cube's position at the intersection point. Here is a script for that:
var yourCube : Transform; //This can be the Layer, but it depends on how your game is made. var height = 0;
function Update () { //The ray from the camera var ray =Camera.main.ScreenPointToRay (Input.mousePosition); //The intersection var hit : RaycastHit;
if(Physics.Raycast(ray,hit)){
//You may need to use Vector2, but I am unfamilar with the method.
yourCube.position = Vector3(hit.point.x,height,hit.point.z);
}
}
Depending on whether your game is completely 2D or just the gameplay is 2D, you may need to change the script. I have already tested it in 3D. Put this script on a World Master game object.
Answer by Statement · Mar 13, 2011 at 04:36 PM
You can get the mouse coorindates from Input.mousePosition. Just use the x/y components to set the position of your box.
Your answer
Follow this Question
Related Questions
How do I change the cursor without a separate Texture2D? 0 Answers
How do i lock my cursor and place it in the middle???? 2 Answers
Multiple mice in Unity 4 Answers
Mouse Input Lag 3 Answers
transform.Translate: object NOT moving toward RaycastHit problem 1 Answer