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 Persona · Nov 09, 2010 at 07:26 PM · rotationmovementplatformer

Rotate to facing direction

Does anyone know how to get a character to rotate and move in the direction of the key they press?

Like pressing the left key makes the character look left and move that way?

I need it for a 2.5D game.

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

6 Replies

· Add your reply
  • Sort: 
avatar image
9
Best Answer

Answer by VS48 · Nov 09, 2010 at 07:48 PM

transform.forward = Vector3.Normalize(new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")));

Edit in response to comment

The transform.forward vector is the "forward" orientation of the transform (the positive Z direction in local space, aka object space). So, when we assign & change this direction, Unity will automatically rotate your object so that its Z axis is the same as our supplied forward vector.

The GetAxis() calls return a value -1 to 1 depending on where the input is positioned along that axis. On the horizontal, -1 is left and 1 is right. On the vertical, 1 is up and -1 is down. So here, new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")), the left-right keys will make the X component of the vector -1 and 1 (respectively), and similarly with the Z axis and the up-down keys.

So the code will give you 8 directions (in 45-degree increments). The default value, when all input is 0, is not defined explicitly.

I was in a rush when I typed that, but a better and much easier solution is only updating when an edge is encountered, for example:

 if (Input.GetKeyDown(KeyCode.W))
        transform.forward = new Vector3(0f, 0f, 1f);
    else if (Input.GetKeyDown(KeyCode.S))
        transform.forward = new Vector3(0f, 0f, -1f);
    else if (Input.GetKeyDown(KeyCode.A))
        transform.forward = new Vector3(1f, 0f, 0f);
    else if (Input.GetKeyDown(KeyCode.D))
        transform.forward = new Vector3(-1f, 0f, 0f);

The GetKeyDown function will return true when the key goes from being released to pressed (when the user starts pressing the key). Something like that should work for 4 directions and I think requires no explanation.

Comment
Add comment · Show 5 · 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 Persona · Nov 09, 2010 at 09:21 PM 0
Share

The forces it to face the Z axis when a button is not pressed and it looks in the direction I'm ai$$anonymous$$g at, but moves in one direction.

Also, can you explain how it works?

avatar image VS48 · Nov 09, 2010 at 10:06 PM 0
Share

See the edit, hope this helps

avatar image Persona · Nov 11, 2010 at 08:45 PM 0
Share

The turning direction is fixed but it still moves in only one direction.

avatar image Persona · Nov 26, 2010 at 01:43 AM 0
Share

Would changing the movement to be based off transform.position work to move it in that direction?

avatar image gl33mer 2 · Nov 28, 2010 at 08:44 AM 0
Share

Hey. I also happen to find this interesting. I'm prototyping a certain Idea...It's 2D. The player moves in whichever direction key he presses but I want to orient the character in that direction. I was thinking that would be a simple task, but it's proven to be tougher than I imagined.

avatar image
9

Answer by willeml85 · May 06, 2012 at 09:03 PM

Create a empty player object and place the below script on it, then put the playergraphics and animations in a child object of player and drag it into the inspector. This is in C#(csharp).

 public class Player : MonoBehaviour {
 
 private float speed = 1.5f;
 public Transform playergraphic;
 
 void  Update (){
 Movement();
 }
 
 void  Movement (){
 
         //Player object movement
 float horMovement = Input.GetAxisRaw("Horizontal");
 float vertMovement = Input.GetAxisRaw("Vertical");
 if(horMovement != 0 && vertMovement != 0){
 speed = 1.0f;
 }else{
 speed = 1.5f;
 }
 transform.Translate(transform.right * horMovement * Time.deltaTime * speed);
 transform.Translate(transform.forward * vertMovement * Time.deltaTime * speed);
 
         //Player graphic rotation
 Vector3 moveDirection= new Vector3 (horMovement, 0, vertMovement);    
 if (moveDirection != Vector3.zero){
 Quaternion newRotation = Quaternion.LookRotation(moveDirection);
 playergraphic.transform.rotation = Quaternion.Slerp(playergraphic.transform.rotation, newRotation, Time.deltaTime * 8);
 }
         //Player graphic animation
 if(moveDirection.magnitude > 0.05f){
 playergraphic.animation.CrossFade("walk", 0.2f);
 }else{
 playergraphic.animation.CrossFade("idle", 0.2f);
 }
 }
 }
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 dragologic · Dec 01, 2012 at 06:08 PM 0
Share

Thanks. You got me good idea.

avatar image seansteezy · Apr 14, 2015 at 10:25 PM 0
Share

@willeml85 has it down, this is exactly what I was looking for! THAN$$anonymous$$ YOU!!!

This was pretty much the exact code that ended up working, except I just set another var called currentRotation and set it to the newRotation after you rotate it. Then I created an else statement for the if (moveDirection != Vector3.zero) part so that whenever you stop moving, you do the same thing but you just Slerp it to the currentRotation, like this: transform.rotation = Quaternion.Slerp(transform.rotation, currentRotation, Time.deltaTime * 8.0f);

I am working on a twin stick shooter kinda like Dead Nation, and this got my movement from 0% to 98%. I ended up having 3 movement states for 2 sticks, those being: no movement, only left stick movement, only right stick movement & left and right movement which is the same as only right movement since the right stick takes over rotation if both are moving and you get a strafe effect. I just have one more thing to figure out :)

avatar image
2

Answer by DeeDeeKaKa · Nov 01, 2013 at 03:05 AM

You could give this a try..

 float faceDirection = Input.GetAxisRaw("Horizontal");
     if(faceDirection != 0)
     {
         transform.forward = new Vector3(faceDirection, 0, 0);
     }

This is just to rotate the character in the proper direction. To move him afterwards, use a

controller.Move(moveDirection * Time.deltaTime)

function. This works for me, and I'm making a 2.5D Platformer

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 Ben 18 · Nov 09, 2010 at 07:42 PM

I am new to unity, but I believe there is an example of this in Standard Assets ThirdPersonController script. I also think there is another example in the platformer tutorial file. http://unity3d.com/support/resources/tutorials/3d-platform-game

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 d.toliaferro · Oct 24, 2012 at 10:03 PM

I don't know if this is "good" code, but it seems to work:

 using UnityEngine;
 using System.Collections;
 
 public class Move : MonoBehaviour {
     bool facingRight;
     // Use this for initialization
     void Start () {
 
     }
 
     // Update is called once per frame
     void Update () {
        if (Input.GetKeyDown (KeyCode.A)) {
          transform.right = new Vector3(-1, 0, 0);
          facingRight = false;
        }
        else if (Input.GetKeyDown (KeyCode.D)) {
          transform.right = new Vector3(1, 0, 0);
          facingRight = true;
        }
        float translate = Input.GetAxis("Horizontal");
 
        if(!facingRight)
          transform.Translate (Vector3.right * -translate * 5 * Time.deltaTime);
        else
          transform.Translate (Vector3.right * translate * 5 * Time.deltaTime);
     }
 }
Comment
Add comment · Show 3 · 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 Bunny83 · Oct 24, 2012 at 10:08 PM 1
Share

Could be simplified to:

 void Update()
 {
     float translate = Input.GetAxis("Horizontal");
     transform.forward = new Vector3(translate, 0, 0);
     transform.Translate (Vector3.forward * $$anonymous$$athf.Abs(translate) * 5 * Time.deltaTime);
 }

But yes, it does work your way, but only when you use WASD. $$anonymous$$eep in $$anonymous$$d that "Horizontal" could be the arrow-keys or a joystick axis.

avatar image d.toliaferro · Oct 24, 2012 at 10:22 PM 0
Share

Hmm, that code makes the guy turn forward once you release the button.

avatar image quaam · May 18, 2013 at 09:48 PM 0
Share

How do you make it so that he stays facing the direction you move? It currently defaults to facing forward when you release the button.

  • 1
  • 2
  • ›

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

7 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Character rotation help needed. 1 Answer

Quaternion.FromToRotation misunderstanding 2 Answers

Rotating towards the mouse. 0 Answers

Erratic behaviour during rotation 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