- Home /
2D Mouse Aiming
Hey guys, I'm creating a 2D sidescroller game and I came across a problem I can't resolve, I've Spent 2 Days googling "2d mouse aiming" and others but I can't find any luck, can someone at least give a suggestion or a script that allows "2d mouse aiming" (an object that actually looks at the mouse cursor and rotates the object on its z axis) on a Sprite or Gameobject in 2d space?
Answer by robertbu · Dec 27, 2013 at 05:10 AM
There have been half a dozen different posts this issue at least since Unity 4.3 came out. I believe most of the code posted should do the job. Here is yet another implementation...a bit different than the other's I've seen:
#pragma strict
function Update () {
var pos = Camera.main.WorldToScreenPoint(transform.position);
var dir = Input.mousePosition - pos;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
sadly this doesn't work, I'm actually planning to modify this hoping it will work
I'm using a different approach so ins$$anonymous$$d of making the object rotate to the cursor i will actually create a custom cursor (a game object in the scene) make it stick to the mouse actual mouse position and than make the object rotate to the custom cursor using "transform.LookAt()" and than 0 out the x and y rotation. I got my script to work but I don't know how to make it follow the cursor WITHIN the game/screen view.
heres what I have
#pragma strict
var mousePos : Vector3;
var cursor : Transform;
function Update () {
mousePos = Input.mousePosition;
cursor.position = (mousePos);
}
The code I posted absolutely does work. I tested it before I posted it, and I just now tested it again. It expects the standard 2D setup of the camera looking towards positive 'z'.
Do the following:
Start a new scene
Create a new Quad or Sprite and attach material or texture
Attach this script to the quad or sprite
Run the app
As for your script, you are mixing screen coordinates and world coordinates. In order to make the script work, you have to decide or derive a distance you want the object from the camera then convert to world coordinates. For example:
public var distanceFromCamera = 10.0;
function Update() {
var pos = Vector3(Input.mousePosition.x, Input.mousePosition.y, distanceFromCamera);
pos = Camera.main.ScreenToWorldPoint(pos);
transform.position = pos;
}
For me robertbu first answer worked, its just simple trigonometry which will most likely be more efficient and accurate than using a gameObject tracking the cursors position.