Making a Object Rotate Based on Mouse Position

Here’s my goal. I’ve been trying to figure this out for awhile now and I haven’t quite got there yet.

I have a tank on my screen. I want to rotate the turret section of the tank towards where the mouse pointer is. I think I can handle this on my own with the Rotate function and GetComponent so at the moment I’m just trying to draw a line from the tank’s position to where the mouse cursor is.

How do I do this?

	Vector3 a = new Vector3(tank.transform.position.x, tank.transform.position.y, 0);
        Vector3 b = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
Debug.DrawLine(a,b);

That’s what I’m trying now but it’s not working.
It draws a weird line that’s way outside my view.

Thanks for the help! :slight_smile:

Hi there.

Think of it this way. Your tank can presumably move to anywhere in the world, so the coordinates might be x=-123, y=-321. These coordinates are in “world space”.

The Input.mousePosition gives you coordinates that are in the screen space of thw window, so will have values from x=0 to x=width-1 and y=0 to y=height-1.

It won’t work to try and draw a line between these two coordinate spaces.

What you need to do is convert the screen coordinates into world coordinates. One way to do this is to convert the screen coordinates into values that vary from -1 to +1. Subtract half the width of the screen from your x mouse coordinate, and then divide by half the width. Do similar for y and half the screen height. This gives you something you can work with. Call this c instead of b.

Now as the tank moves you can draw lines from it outwards. Scale the vector c by the size of your tank*5, and add a to it, call this d. Now draw your lines from a to d and you should have something closer to what you want.

Now what you will need to think about is how the turret should rotate in addition to the tank rotating. Also, it might be confusing for your players if the camera that is looking at your tank can rotate. These are more complex problems to solve.

Hope this helps,
Graham

Thanks for the advice.
I am aiming to make a game like the “Tanks!” game from Wii Play.
I’ve attached what I’ve accomplished so far.

180326–6429–$tanks_128.zip (530 KB)