Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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
0
Question by MagicalBilly · May 20, 2016 at 05:09 AM · c#rotationmovement

How can I get my character to move forward in the direction of the camera?

I currently have the following class. The class is supposed to be a custom character controller that allows the player to walk on non-horizontal surfaces, and so far most of it has been working, except for direction-based movement.

 using UnityEngine;
 using System.Collections;
 
 namespace Normal
 {
     /// <summary>
     /// This class is responsible for managing the various aspects of the player,
     /// from simple movement to mesh alignment.
     /// </summary>
     [RequireComponent(typeof(Rigidbody))]
     public class PlayerController : MonoBehaviour
     {
         public float RotationTransitionSpeed = 1.0f;
         public float Sensitivity = 2.0f;
         public float MovementSpeed = 5.0f;
         public float RaycastDistance = 10.0f;
         public float GravityForce = 9.8f;
         public Vector3 GravityVector = new Vector3(0, -1, 0);
 
         private Quaternion _TargetRotation;
         private float _VerticalCameraRotation;
         private Vector3 _MovementDistance;
         private Vector3 _MovementVelocity;
         private Rigidbody _Rigidbody;
 
         /// <summary>
         /// Apply movement to the player object based on specific key inputs. The player can currently
         /// move forwards, backwards, left and right.
         /// </summary>
         public void ApplyMovement()
         {
             Vector3 movementDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
             Vector3 movementVector = movementDirection * this.MovementSpeed * Time.deltaTime;
             this.transform.Translate(movementVector);
         }
 
         /// <summary>
         /// Apply rotation to the player based on the normal of the face they're
         /// "above". This function will also set the gravity of the player accordingly.
         /// </summary>
         public void ApplyRotation()
         {
             // Apply rotation to the player and the camera objects based on the movement of
             // the mouse cursor.
             Camera.main.transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * this.Sensitivity);
             this._VerticalCameraRotation += Input.GetAxis("Mouse Y") * this.Sensitivity;
             this._VerticalCameraRotation = Mathf.Clamp(this._VerticalCameraRotation, -60, 60);
             Camera.main.transform.localEulerAngles = new Vector3(
                 Vector3.left.x * this._VerticalCameraRotation,
                 Camera.main.transform.localEulerAngles.y,
                 0
             );
 
             // Apply rotation to the entire player object based on where they are walking
             // on a specific mesh.
             RaycastHit raycastHit;
             if(Physics.Raycast(this.transform.position, -this.transform.up, out raycastHit))
             {
                 this._TargetRotation = Quaternion.FromToRotation(Vector3.up, raycastHit.normal);
                 this.GravityVector = -raycastHit.normal;
             }
 
             this.transform.rotation = Quaternion.Lerp(
                 this.transform.rotation, 
                 this._TargetRotation, 
                 Time.deltaTime * this.RotationTransitionSpeed
             );
         }
 
         /// <summary>
         /// Apply a gravity force to the player based on the currently set gravitational
         /// force. Gravitational force direction is determined based on the normal that
         /// the player is "above".
         /// </summary>
         public void ApplyGravity()
         {
             this._Rigidbody.AddForce(this.GravityVector * this.GravityForce * this._Rigidbody.mass);
         }
 
         /// <summary>
         /// FixedUpdate is called a set amount of times per frame in sync with the physics engine.
         /// </summary>
         public void FixedUpdate()
         {
             this.ApplyGravity();
         }
 
         /// <summary>
         /// Update is called once per frame.
         /// </summary>
         public void Update()
         {
             this.ApplyRotation();
             this.ApplyMovement();
         }
 
         /// <summary>
         /// Start is called once.
         /// </summary>
         public void Start()
         {
             this._Rigidbody = this.GetComponent<Rigidbody>();
         }
     }
 }

Ideally, I'd like to have the player move forward relative to the direction the camera is facing, but I cannot for the life of me figure out how to do this. Is it possible?

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

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by 5c4r3cr0w · May 20, 2016 at 05:19 AM

In Order to do that you need to take a vector that is represented by positions of player and camera. So consider taking that direction like :

 this._RigidBody.position - Camera.main.transform.position.

after that you can normalise this vector and multiply desired float according to your input.

Comment
Add comment · Show 2 · 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 MagicalBilly · May 20, 2016 at 11:41 AM 0
Share

I probably should have mentioned that this is intended to be a first person controller and that the camera is a child of my player object.

avatar image 5c4r3cr0w MagicalBilly · May 20, 2016 at 12:32 PM 0
Share

If that's the case then use transform.forward ins$$anonymous$$d of above resultant vector.

avatar image
0

Answer by ninja_gear · May 20, 2016 at 02:06 PM

the important part of what u want is

 public void ApplyMovement()
          {
              Vector3 movementDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
              Vector3 movementVector = movementDirection * this.MovementSpeed * Time.deltaTime;
              this.transform.Translate(movementVector);
          }

most specifically the line

 Vector3 movementDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
 

what you need to do as commented earlier is to make sure the movement direction isnt based on the world space of zero rotation, but based on the rotation of the camera:

          public void ApplyMovement()
          {
              Vector3 movementDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
              Vector3 movementRelativeToCamera = Quaternion.Euler(Camera.main.transform.rotation) * movementDirection;
              Vector3 movementVector = movementRelativeToCamera * this.MovementSpeed * Time.deltaTime;
              this.transform.Translate(movementVector);
          }

Working with Quaterion's is the next step after working with vectors when you start to build a camera. This code is 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

Flip over an object (smooth transition) 3 Answers

Making a bubble level (not a game but work tool) 1 Answer

Objects not always Spawning At Correct Location 2 Answers

Distribute terrain in zones 3 Answers

Problems after rotating character. 0 Answers


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