I am trying to get my character to look to where my mouse is pointing while using the wasd keys for movement. I have tried several different scripts but none have worked. I’m not sure what it is that is hindering my character from turning. Any suggestions?
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}
public class PlayerController : MonoBehaviour
{
public float speed;
Vector3 movement;
public Boundary boundary;
new Rigidbody rigidbody;
int floorMask;
float camRayLength = 100f;
public GameObject shot;
public Transform shotSpawn;
public float fireRate;
private float nextFire;
void Update()
{
if (Input.GetButton ("Fire1") && Time.time > nextFire) {
nextFire = Time.time + fireRate;
Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
GetComponent<AudioSource>().Play ();
}
}
void Start()
{
floorMask = LayerMask.GetMask("Floor");
rigidbody = GetComponent<Rigidbody> ();
}
void FixedUpdate ()
{
float h = Input.GetAxis ("Horizontal");
float v = Input.GetAxis ("Vertical");
Move(h, v);
Turning();
rigidbody.position = new Vector3
(
Mathf.Clamp(rigidbody.position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp(rigidbody.position.z, boundary.zMin, boundary.zMax)
);
}
void Move(float h, float v)
{
movement.Set(h, 0f, v);
movement = movement.normalized * speed * Time.deltaTime;
rigidbody.MovePosition(transform.position + movement);
}
void Turning()
{
Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit floorHit;
if (Physics.Raycast(camRay, out floorHit, camRayLength, floorMask))
{
Vector3 playerToMouse = floorHit.point - transform.position;
playerToMouse.y = 0f;
Quaternion newRotation = Quaternion.LookRotation(playerToMouse);
rigidbody.MoveRotation(newRotation);
}
}
}
There are a few tiny issues. For one, I think you want the inverse of floorMask (~floorMask) to pass into the raycast check.
Also, I changed the contents of your “if” statement block to simply be:
if (Physics.Raycast(camRay, out floorHit, camRayLength, ~floorMask))
{
transform.LookAt ( floorHit.point);
}
Now when I did that, the act of rotating the rigidbody “drives” it funny on the map, so it is probably best to rotate a sub component of the player rather than his rigidbody. I will leave that change to you!