2D mouselook

Does anyone know how I could perform a 2D sidescroller mouselook? Basically I want the sprit’s arm and weapon to look at where the mouse is pointing. How can I do this? Any ideas?

Thanks.


Edit: What I’ve tried:

Place a collider object flush with sprites and raycast from the mouse position. Get the racast hit point and use the LookAt function on the arm.

Problems:

  • LookAt is a 3d function so a 1-sided “plane” mesh will not work well as there is no way to define the way the arm sprite faces when it looks at the point. This results in the visible side of the mesh not facing the camera.
  • The arm sprite is parented to the player so the arm’s geometry is scaled to the player. This makes it hard to do complex angle movements I think?
  • The arm does not hinge properly at the elbow joint.
  • Due to the LookAt function being mainly for 3d uses unnecessary calculations are taking place. I only need to rotate the plane on the x and y.

Hi there,
so I don’t work much with 2D sprites so I have only tested this on a camera and box but it worked so hopefully you can add and edit part for it to work for you.

This is the code I ended up with:

var Sprite : Transform;
var point1 : Vector3;

function Update () {
	point1 = camera.ScreenToWorldPoint (Vector3(Input.mousePosition.x, Input.mousePosition.y, camera.nearClipPlane));
    print(point1);
	
	Sprite.LookAt(Vector3(point1.x, point1.y, Sprite.position.z));
}

My set up had my camera looking down the z axis so that only the x and y axis could be seen. I used the mouse input to convert the mouse point to a world point. I then made the sprite look at the point but only the x and y values of it. the z value that it looks at is its own z position so it never rotates in any direction other than along the z axis.

hope that helps

Scribe

LookAt is a 3d function so a 1-sided “plane” mesh will not work well as there is no way to define the way the arm sprite faces when it looks at the point. This results in the visible side of the mesh not facing the camera.

I was able to fix this by simply rotating the sprite so that at runtime the rendered side is facing the proper way during the LookAt function.

This code from a mouse-drag camera ought to serve your purposes. Create a plane at the depth of your 2d stuff, and raycast to it. Use lookat on the hit point.

mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
groundPlane.Raycast(mouseRay, out hitDist);
Vector3 dragPoint = mouseRay.GetPoint(hitDist);

I noticed part of your problem with lookat was the nature of your sprites. I would recommend rotating your whole scene so that “forward” for the sprites is “right” from your viewport.

I think there is a world to 2d Point function.