Hi.
I’m trying to make a tank shooter game, and I have a small problem with my turret mouselook.
I use Plane.Raycast to rotate the turret towards the mouse position, but it only works for sideways and downwards rotation. When I move the cursor above the middle of the screen (y-axis), the tank’s turret won’t rotate towards the mouse anymore.
Here is the code I’m currently using:
public class PlayerTankController : MonoBehaviour {
private Transform turret;
private Transform bulletSpawnPoint;
Plane ground;
void Start() {
turret = transform.Find("Turret");
bulletSpawnPoint = turret.GetChild(0).transform;
ground = new Plane(Vector3.up, transform.position);
}
void Update() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float dist = 0.0f;
if(ground.Raycast(ray, out dist)) {
Vector3 clickPoint = ray.GetPoint(dist);
turret.LookAt (clickPoint);
bulletSpawnPoint.LookAt(clickPoint);
}
}
I’m going to guess this is a first-person perspective from the turret point-of-view. If so, above a certain point, your ray does not intersect the plane, so the Plane.Raycast() fails. Depending on the nature of your game, you have a couple of choices. First, if you only want the turret to shoot when there is something in the crosshairs, then replace your Plane.Raycast() with a Physics.Raycast(). If you want the tank to shoot at all the time, then when the Plane.Raycast() fails, you want to do a fallback calculation for the aim point. Pick a distance from the camera for this fallback point, then use Camera.ScreenToWorldPoint() based on this distance. Be sure you set the ‘z’ of the point passed to this function to the fallback distance.