I have a cannon that is suppose to rotate and face the face the mouse. The cannon should only rotate only its z axis so it goes up and down. The game is 2.5d.
Here is my closest attempt at doing this. It rotates right again but it doesn't follow the mouse.
Can anyone help me? I can't figure out how to fix my code.
Input.GetAxis("Mouse x") is reading the deltaX of the mouse (how much the mouse is moved in the X-axis each frame. If you want the gun to follow the mouse, you need it to turn toward either where the mouse is pointing on the terrain or where it is on the screen. For where it is pointing in the world or on the terrain, you would need to Physics.Raycast With a ScreenPointToRay, or using the ScreenToWorldPoint of the mouse position (don't forget to invert the mouse Y-axis when using it in the ScreenToWorldPoint: just subtract it from Screen.height to do so easily) to get the actual point on the surface. Then you rotate your cannon to face that point.
Or you can use WorldToScreenPoint to get your angle between your cannon and the position of the mouse, and move accordingly.
You'll have to decide which of these approaches fits your vision of the cannon movement best. Give one of them a try and we'll help you from there...
answered Jan 20 '11 at 10:29 PM