Aiming a turret at mouse position

Hey guys,

I have a turret that I need to aim wherever the mouse pointer is. I’m using a perspective camera, so I can’t just use “ScreenToWorldPoint(Input.mousePosition)” and call it a day.

So what I came up with is this:

``````public Transform target;
public Transform partToRotate;
private Camera cam;

private void Start()
{
cam = Camera.main;
}

private void Update()
{
float zOffset = cam.transform.position.z;
target.transform.position = cam.ScreenToWorldPoint(Input.mousePosition + new Vector3(0, 0, zOffset));

Vector2 direction = target.position - partToRotate.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90f;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
partToRotate.rotation = Quaternion.Slerp(partToRotate.rotation, rotation, speed * Time.deltaTime);
}
``````

It does exactly what I wanted it to do, except for one thing:

The turret aims in the opposite direction of the mouse pointer.

I’m sure this is something simple to fix, but I’m not the sharpest pencil in the box, and I can’t figure out which thing I need to flip to get this working properly.
Help a brother out?

i was going to post that for getting the direction from A to B you should do B - A but pretty sure you are doing it all right, i went to test it and it is working fine for me, but if ou want to inverse the direction you can just do Vector2 direction = partToRotate.position - target.position; the only reason i can find to this is that you are using the target fot the partToRotate object and the partToRotate object as target

I’m a bit of a noob, so sorry if this is way off, but I had a similar requirement and used raycasting. Cast a ray from the camera to the mouse pointer, and where it hits something you get a 3D point. Just use this point for your turret to LookAt…
Maybe not as elegant as your solution, but might be worth a Look (excuse deliberate pun!)