Search Unity

How to make 2D sprite face movement Direction

Discussion in 'Editor & General Support' started by DarkOdeus, Jun 27, 2014.

  1. DarkOdeus

    DarkOdeus

    Joined:
    Jul 2, 2013
    Posts:
    9
    I am starting a new project with 2D and I got the character to move using this script. This is a top down script so it should face up down left and right

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class PlayerController : MonoBehaviour
    5. {
    6.     public float speed;
    7.  
    8.     void FixedUpdate ()
    9.     {
    10.         float moveHorizontal = Input.GetAxis ("Horizontal");
    11.         float moveVertical = Input.GetAxis ("Vertical");
    12.  
    13.         Vector2 movement = new Vector2 (moveHorizontal, moveVertical);
    14.         rigidbody.velocity = movement * speed;
    15. }
    16. }
    This moves the character along the y and the x axis but does not rotate them. What is the easiest way to make the character look where they are walking

    Push D move right face right
    Push A move left face left etc

    It seems to be worth noting my artist is making sprites for each direction. How would I code this in for the movement animation as well?
     
  2. Reaner

    Reaner

    Joined:
    Nov 19, 2013
    Posts:
    1
    Try:

    transform.up = rigidbody2D.velocity.normalized;

    every frame.

    EDIT: If you have a sprite for each direction you can use the animation system to have different states for each direction. Use your horizontal and vertical input to determine which direction the player if moving and enter the relevant animation state.
     
  3. DarkOdeus

    DarkOdeus

    Joined:
    Jul 2, 2013
    Posts:
    9
    Adding it gave me a complier error. It's not taking the transform command
     
  4. Brutang

    Brutang

    Joined:
    Nov 1, 2013
    Posts:
    23
    DarkOdeus: It looks like in your script you're using a rigidbody, not a rigidbody2D as Reaner's script uses. That might be the error, so give that a try?


    You should probably be using a rigidbody2D for your 2d sprites/characters anyway if you're making a 3d game as far as I know. The only 3d elements I use in my 2d platformer are 3d colliders for particle collision as when I started making it there was no 2d particle collision system.
     
  5. DarkOdeus

    DarkOdeus

    Joined:
    Jul 2, 2013
    Posts:
    9
    Is the conversion to rigidbody2d simple. When I wrote the code I attempted to use a rigidbody2d and it would not take.
     
  6. DarkOdeus

    DarkOdeus

    Joined:
    Jul 2, 2013
    Posts:
    9
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class PlayerController : MonoBehaviour
    5. {
    6.     public float speed;
    7.  
    8.     void FixedUpdate ()
    9.     {
    10.         float moveHorizontal = Input.GetAxis ("Horizontal");
    11.         float moveVertical = Input.GetAxis ("Vertical");
    12.  
    13.         Vector2 movement = new Vector2 (moveHorizontal, moveVertical);
    14.         rigidbody2d.velocity = movement * speed;
    15.    
    16. }
    17. }
    This is the updated code with a rigidbody2d. The compiler error I get is saying that rigidbody2d does not exist in this context. How would I fix this?
     
  7. Brutang

    Brutang

    Joined:
    Nov 1, 2013
    Posts:
    23
    The GameObject you're attaching the script to must have a RigidBody2D component, not a RigidBody.

    Also, it has to be rigidbody2D with a capital D.

    As far as converting it from RigidBody to RigidBody3D you're fine in the code, nothing you need to change at all.

    Edit: I just tested your script and it works fine with the capital D.

     
    Last edited: Jun 28, 2014
  8. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,438
    and that should be big D:
    rigidbody2D.velocity = movement * speed;
     
  9. DarkOdeus

    DarkOdeus

    Joined:
    Jul 2, 2013
    Posts:
    9
    Got it to work with the Big D. Such a newbie mistake :p
     
  10. DarkOdeus

    DarkOdeus

    Joined:
    Jul 2, 2013
    Posts:
    9
    The character now moves but I have a slight issue. I applied the line transform.up = rigidbody2D.velocity.normalized; to my script and since the camera is bound to the character it rotates so the character is always moving up. How do I make it so it does not rotate the camera. Is there a setting for the camera to lock rotation during gameplay
     
  11. DarkOdeus

    DarkOdeus

    Joined:
    Jul 2, 2013
    Posts:
    9
    Two issues. One. I have the camera parented to the player so the player rotation works but it rotates the camera as well. How do I stop this? Also when the player stands idle the return to the start position (facing towards the top of the screen for example) is there any way to make it so the character does not idle like that IE. Stay facing the direction they were even when stopped
     
  12. Brutang

    Brutang

    Joined:
    Nov 1, 2013
    Posts:
    23
    You'd be much better off not parenting the camera to the player, instead have the camera it's own thing with a script to follow the player.

    Code (JavaScript):
    1. var player:Transform;
    2. var xOffset:float;
    3. var yOffset:float;
    4.  
    5. function Awake()
    6. {
    7.     player=GameObject.Find("Player").transform;
    8. }
    9.  
    10. function Update()
    11. {
    12.     transform.position.x=player.position.x+xOffset;
    13.     transform.position.y=player.position.y+yOffset;
    14. }
    Then in the inspector you can set the xOffset and yOffset if you don't want the camera to be dead center on the player; otherwise just leave them at 0. Also change ("Player") to whatever you're controlling.
     
  13. DarkOdeus

    DarkOdeus

    Joined:
    Jul 2, 2013
    Posts:
    9
    Anyway you have a C# conversion of this. It's currently my primary language (learning) and I want to keep all the code of my game the same language
     
  14. Brutang

    Brutang

    Joined:
    Nov 1, 2013
    Posts:
    23
    I primarily use JavaScript so there might be a more efficient way of doing this, but I tested it and it works.

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. class CameraFollow: MonoBehaviour {
    6.  
    7.    Transform player;
    8.    public float xOffset=0;
    9.    public float yOffset=0;
    10.    public float zOffset=0;
    11.    Vector3 playerPosition;
    12.  
    13.    void Start()
    14.    {
    15.      player = GameObject.Find ("Player").transform;
    16.    }
    17.  
    18.    void  Update ()
    19.    {
    20.      playerPosition.x = player.position.x + xOffset;
    21.      playerPosition.y = player.position.y + yOffset;
    22.      playerPosition.z = player.position.y + zOffset;
    23.      transform.position = playerPosition;
    24.    }
    25.  
    26. }
    27.  
     
    Last edited: Jul 1, 2014
  15. A_Random_Stranger_Online_

    A_Random_Stranger_Online_

    Joined:
    Jul 10, 2023
    Posts:
    4
    i read this post for about 3 times and no matter what i did i still cant get my 2D Character to face the direction of movement. im a 3D Game dev and this is my first 2D Game and im facing a lot of issues but i fixed all of them =. i just wanna fix this one but i couldnt fix it on my own and there araent any helpful tutorials, can anyone help or am i simply stupid?
    This is my script:

    Code (CSharp):
    1. public class Movement : MonoBehaviour
    2. {
    3.     public float Force;
    4.     public float GroundDist;
    5.     public LayerMask GroundMask;
    6.     public bool IsGrounded;
    7.     public Transform GroundCheck;
    8.     public float MaxDegreesDelta = 360f;
    9.  
    10.     public void FixedUpdate()
    11.     {
    12.         float x = Input.GetAxisRaw("Horizontal");
    13.  
    14.         Vector3 MoveDir = new Vector3(x, 0f, 0f).normalized;
    15.  
    16.         if(MoveDir.magnitude >= 0.01f)
    17.         {
    18.             transform.up +=  MoveDir * Force * Time.deltaTime;
    19.         }
    20.     }
    21. }
     
  16. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,739
    This thread is ten years old. Please don't necro-post.

    If you have a new question, make a new post. It's FREE!!





    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    This is the bare minimum of information to report:

    - what you want
    - what you tried
    - what you expected to happen
    - what actually happened, log output, variable values, and especially any errors you see
    - links to actual Unity3D documentation you used to cross-check your work (CRITICAL!!!)

    The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven't put effort into finding the documentation, why should we bother putting effort into replying?



    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    - Do not TALK about code without posting it.
    - Do NOT post unformatted code.
    - Do NOT retype code. Use copy/paste properly using code tags.
    - Do NOT post screenshots of code.
    - Do NOT post photographs of code.
    - Do NOT attach entire scripts to your post.
    - ONLY post the relevant code, and then refer to it in your discussion.



    Anytime you need more information about what your program is doing as well as how and where it is deviating from your expectations, that means it is...



    Time to start debugging!

    By debugging you can find out exactly what your program is doing so you can fix it.

    Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    If your problem is with OnCollision-type functions, print the name of what is passed in!

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    If you are looking for how to attach an actual debugger to Unity: https://docs.unity3d.com/2021.1/Documentation/Manual/ManagedCodeDebugging.html

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.