- Home /
Moving in the direction of mouse
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.
Answer by arul20 · Oct 23, 2017 at 09:13 AM
Late answer, but I couldn't find this simple answer anywhere on the web, so updating in 2017.
This is how I did it (basically using AddRelativeForce instead of AddForce) (Added more details on another related question):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ctrlFPS : MonoBehaviour {
private Rigidbody rb;
private float xForce;
private float zForce;
private Vector3 force;
private float pitch =0.0F;
private float yaw =0.0F;
void Start(){
rb = GetComponent<Rigidbody> ();
}
void FixedUpdate (){
xForce = Input.GetAxis ("Horizontal");
zForce = Input.GetAxis ("Vertical");
pitch -= Input.GetAxis ("Mouse Y");
yaw += Input.GetAxis ("Mouse X");
}
void LateUpdate(){
force = new Vector3 (xForce, 0.0F, zForce);
// rotate object to face mouse direction
rb.transform.localEulerAngles = new Vector3 (pitch, yaw, 0.0F);
// move object in facing direction relative to local (AddRelative) not world (AddForce) coordinates
rb.AddRelativeForce (force);
}
}
Answer by SnStarr · Jan 19, 2015 at 11:46 AM
Try Input.MousePosition play around with that, instead of getting the RawAxis values for Move()
Input.$$anonymous$$ousePosition seems to have a lot of potential, but unfortunately, it refuses to work. It turns red and I get an error.
Answer by chariot · Jan 19, 2015 at 12:17 PM
Some sort of
#pragma strict
public var speed : float;
private var mousePos : Vector2;
private var screenPos : Vector3;
private var dx : float;
private var dz : float;
private var theta : float;
function Start () {
}
function Update () {
Move();
}
function Move () {
mousePos = Input.mousePosition;
screenPos = camera.main.ScreenToWorldPoint(Vector3(mousePos.x, mousePos.y, transform.position.z - camera.main.transform.position.z));
transform.rotation.eulerAngles.z = Mathf.Atan2((screenPos.y - transform.position.y), (screenPos.x - transform.position.x))*Mathf.Rad2Deg;
theta = transform.rotation.eulerAngles.z * 3.14 / 180.0;
dx = Mathf.Cos(theta);
dz = Mathf.Sin(theta);
transform.position.x = transform.position.x + dx*speed;
transform.position.z = transform.position.z + dz*speed;
}
Code in JS and untested
Your answer
![](https://koobas.hobune.stream/wayback/20220613180831im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Tracking HTC Vive Controller Motion Direction? 1 Answer
How to make the turret of a tank in a 3rd person game look at the mouse cursor? 1 Answer
How to make my spaceship move by mouse? 2 Answers
Trying to move my gameobeject in a certain direction (2D, C#) 1 Answer