I'm trying to use Physics.Raycast to rotate the player to face the mouse cursor but it's not working like it should
I recently took up Unity and decided to make some of their tutorial games. The problem I'm facing is with the Survival Shooter game. Here's my code:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6.0f;
private Vector3 movement;
private Animator anim;
private Rigidbody rb;
private int floorMask;
private float camRayLength = 100.0f;
private void Awake()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody>();
floorMask = LayerMask.GetMask("Floor");
}
private void FixedUpdate()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Move(horizontal, vertical);
Turning();
Animating(horizontal, vertical);
}
void Move(float h, float v)
{
movement.Set(h, 0.0f, v);
movement = movement.normalized * speed * Time.deltaTime;
rb.MovePosition(transform.position + movement);
}
void Turning()
{
Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit floorHit;
if (Physics.Raycast(camRay, out floorHit, camRayLength, floorMask))
{
Debug.Log("Hello");
Vector3 playerToMouse = floorHit.point - transform.position;
playerToMouse.y = 0.0f;
Quaternion newRotation = Quaternion.LookRotation(playerToMouse);
rb.MoveRotation(newRotation);
}
}
void Animating(float h, float v)
{
bool walking = h != 0.0f || v != 0.0f;
anim.SetBool("IsWalking", walking);
}
}
The problem is in the Turning() function. What's supposed to happen is that the player should turn to face the mouse cursor, but that's not happening. As you can see, there's a line in there that says "Debug.Log("Hello")". However, it's not logging, which means that something is wrong, I just don't know what. I followed the tutorial and I thought I did everything right. Guess not.
Any help would be appreciated.
Your answer
Follow this Question
Related Questions
Gun RayCast Origin lags with fast moving object. Help? 0 Answers
How can I incorporate a Rotation Towards the Mouse Position into this Script? I Tried. 0 Answers
How to make a Physics.Raycast detect a FPSController? 0 Answers
Character rotation, only happens when mouse is rotated around world centre (0,0,0) 0 Answers