- Home /
Object where the mouse is
Hi all,
Im trying to make an 2D breakout game where I use the mouse in X and Y-position. All tutorials i've found uses the keyboard.
Is there anyone that maybe can help or get me going with the script?
Sorry if its a newbiequestion.
I read this question as saying How can I calculate and use the changes in mouse movement for Input X and Y values (like Touch.deltaPosition but for mouse). Is this what you mean? If so, check my answer here : http://answers.unity3d.com/questions/332013/calculating-change-in-mouse-position.html
Answer by Melanina · Feb 19, 2013 at 02:45 PM
this should be what you want.
gameObject.transform.position = Camera.main.ScreenToWorldPoint ( Input.mousePosition );
Answer by arkon · Feb 19, 2013 at 01:49 PM
Try using Input.mousePosition, it is a vector3 of the mouse position.
Answer by Professor Snake · Feb 19, 2013 at 01:54 PM
You can use a raycast that originates from the camera, whose direction is the mouse's position:
var hit:RaycastHit;
var mask:LayerMask;
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray,hit, 500,mask)) {
//do something at hit.point, which is the point at which the raycast hit a collider
}
EDIT: I apologise, i misunderstood your question. I will keep my answer up however in case it helps.
Answer by robertbu · Feb 19, 2013 at 03:57 PM
Both @Professor Snake and @Melanina solutions will work, but what they they wrote will only take you half way. For using ScreenToWorldPoint() you need to set the Z parameter to the distance in front of the camera you want to find. If your camera is looking at positive Z, this code would be attached to the paddle (Untested):
void Update() {
Vector3 v3Pos = Input.mousePosition;
// Get distance the paddle is in front of the camera
v3Pos.z = Mathf.Abs(transform.position.z - Camera.main.transform.position.z);
v3Pos = Camera.main.ScreenToWorldPoint (v3Pos);
// Don't want to move the paddle up and down, just x
v3Pos.y = transform.position.y;
transform.position = v3Pos;
}
For @Professor Snake's solution, you would need to construct a mathematical plane at the distance the paddle is from the camera. Then you would use Plane.Raycast() with the ray he constructed to find the screen point in world space.
Your answer
Follow this Question
Related Questions
Mouse Aiming Follow Wrong Direction - Help 2 Answers
Need Help: Unity draw-to-follow? 0 Answers
Run script when object is clicked 1 Answer