- Home /
Question by
Aaron_Moseley · Jan 19, 2019 at 11:02 PM ·
scripting problemmovementplayerraycastingmovement script
My player doesn't turn based on the mouse when it's supposed to
My player is supposed to turn/rotate based on the position of the mouse. I'm using a slightly modified version of the survival shooter code, but with a different character than in the tutorial. The character still moves with WASD, but doesn't turn. I'm also seeing no errors. Thanks for any help.
public class PlayerMovement : MonoBehaviour
{
public float currentSpeed;
public float walkingSpeed = 6f;
public float sprintSpeed = 12f;
Vector3 playerToMouse;
Vector3 movement;
Animator anim;
Rigidbody playerRigidbody;
int floorMask;
float camRayLength = 100f;
bool sprint;
void Awake()
{
currentSpeed = walkingSpeed;
floorMask = LayerMask.GetMask("Floor");
anim = GetComponent<Animator>();
playerRigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
float h = Input.GetAxisRaw ("Horizontal");
float v = Input.GetAxisRaw ("Vertical");
Move (h, v);
Turning ();
Animating (h, v);
Sprint();
}
void Sprint ()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
currentSpeed = sprintSpeed;
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
currentSpeed = walkingSpeed;
}
}
void Move (float h, float v)
{
movement.Set (h, 0f, v);
movement = movement.normalized * currentSpeed * Time.deltaTime;
playerRigidbody.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);
playerRigidbody.MoveRotation (newRotation);
}
}
void Animating (float h, float v)
{
bool walking = h != 0f || v != 0f;
anim.SetBool ("IsWalking", walking);
}
}
Comment