Don_Huan
Don_Huan

Reputation: 85

Raycast Mouse Controller ,difference between player and mouse point(Survival Shooter Tutorial)

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);
}
}

Upvotes: 1

Views: 104

Answers (1)

captainCrazy
captainCrazy

Reputation: 132

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.

Upvotes: 3

Related Questions