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.
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.
this should be what you want.
gameObject.transform.position = Camera.main.ScreenToWorldPoint ( Input.mousePosition );
Try using Input.mousePosition, it is a vector3 of the mouse position.
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.
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.