Hello, I recently began scripting in C#/Unity, so the code I’m using is derivative of the player movement script from the survival shooter tutorial.
The way it is now, the player can move along the global X and Z axis, and the player model is rotated so it looks in the direction of the mouse.
I’ve added in another script, which rotates the camera, so naturally the movement along the global axes is irrelevant when the camera is facing a different direction. Naturally, the rotation part of the script is unaffected.
How can I change the movement script so that the player moves in the direction of the mouse, and not along these set axes?
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
//scripts not under void begin here
public float speed = 6f; //f denotes floating point variable
Vector3 movement; //stores player speed
Animator anim;
Rigidbody playerRigidBody;
int floorMask; //Light will only hit floor
float camRayLength = 100f; //length of ray
public GameObject food;
void Awake(){ //sets up and activates variables previously defined
floorMask = LayerMask.GetMask ("Floor"); //defines a mask on the floor defined in the assets folder
anim = GetComponent <Animator> (); //this and rigibody simply activate the assets in the main unity file
playerRigidBody = GetComponent <Rigidbody> ();
}
void FixedUpdate(){ //deals with physics
float h = Input.GetAxisRaw ("Horizontal");// raw axis has a 0 or 1 value, no non-integer. this makes the player move better and straighter. previously uses GetAxis, made player move strange
float v = Input.GetAxisRaw ("Vertical");
Move (h, v);
Turning ();
}
void Move (float h, float v){
movement.Set (h, 0f, v); //makes movement speed based on the axis of movement H/V
movement = movement.normalized * speed * Time.deltaTime; //deltaTime is the time between each update, so that movement by normal speed won't rapidly speed out
playerRigidBody.MovePosition (transform.position + movement);
}
void Turning (){
Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition); //illuminates in the direction of the mouse
RaycastHit floorHit; //floorHit variable stores what the cast ray hits
if (Physics.Raycast (camRay, out floorHit, camRayLength, floorMask)) { //identifies the ray in question, the object hit, and the layer on which the ray acts (floor)
Vector3 playerToMouse = floorHit.point - transform.position; //creates a vector from Player to floorHit
playerToMouse.y = 0f; //solidifies the vector on the floor
Quaternion newRotation = Quaternion.LookRotation (playerToMouse); //based on the vector, establish a new rotation
playerRigidBody.MoveRotation (newRotation); //rotate the player to the quaternion
}
}
}
Thanks for any help anyone can offer me.