1
votes

I'm trying to understand the code of the PlayerController made by Unity(Survival Shooter Tutorial).I understand everything, except the reason, why they wrote the difference between FLOOR-POINT(where the mouse is directed) and the player (transform position).I tried to write only the floor point without the player position and its worked.Why they wrote that? Maybe someone passed this tutorial and can help me with that?

Unity tutorial : https://unity3d.com/learn/tutorials/projects/survival-shooter/player-character?playlist=17144

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

public float speed= 6f;

Vector3 movement;
Animator anim;
Rigidbody playerRigidbody;
int floorMask;
float camRayLength=100f; 

void Awake()
 {

    floorMask = LayerMask.GetMask("Floor");

    anim = GetComponent<Animator> ();
    playerRigidbody = GetComponent<Rigidbody> ();

}

void FixedUpdate()
{
    float v = Input.GetAxisRaw ("Vertical");
    float h = Input.GetAxisRaw ("Horizontal");

    Move (h, v);
    Turning ();
    Animating(h,v);

}

void Move(float h,float v)
{

    movement.Set (h,0f,v);

    movement = movement.normalized * speed * 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 wakling = h != 0f || v != 0f;  
    anim.SetBool("IsWalking",wakling);
}
}
1
Did you try not having the player at (0,0,0) when the code ran? - Evan Knowles
Yes,I tried it now and it still work! - Don_Huan
I think it is so the player face the position where the mouse is. For example try going in a corner and then click right back the player. The player will face the corner and not the mouse position - Ludovic Feltz

1 Answers

3
votes

Raycasts need a direction, which is usually given as (someVector - someOtherVector). The result from this subtraction is a new vector that takes someVector as the origin point. In your case, the relative vector from the mouse to the player probably never changes, so the subtraction seems not needed. However, it is good practice to use the subtraction of two vectors as direction.