Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by ustulo · Jan 19, 2015 at 07:46 AM · c#movementmousedirection

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.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
1

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


Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

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()

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ustulo · Jan 19, 2015 at 11:24 PM 0
Share

Input.$$anonymous$$ousePosition seems to have a lot of potential, but unfortunately, it refuses to work. It turns red and I get an error.

avatar image
0

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

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges