- Home /
Plane.Raycast for mouselook won't work in positive y-axis
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);
}
}
Do anyone know how to fix this?
Answer by robertbu · Jan 23, 2014 at 09:31 PM
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.
The code might look like:
Vector3 clickPoint = Vector3.zero;
if(ground.Raycast(ray, out dist)) {
Vector3 clickPoint = ray.GetPoint(dist);
}
else {
clickPoint = Input.mousePosition;
clickPoint.z = defaultDistance;
clickPoint = Camera.main.ScreenToWorldPoint(clickPoint);
}
bulletSpawnPoint.LookAt(clickPoint);
turret.LookAt (clickPoint);
Your answer
Follow this Question
Related Questions
Unity Android Movement Problem 0 Answers
draw line between mouse and gameobject on flat plane 0 Answers
smooth raycast LookAt ? 1 Answer
Intersection point of mouse with ZX plane 1 Answer
Mouse plane does not detect height 1 Answer