Advertisement
romi_fauzi

TopDownPlayer

Feb 2nd, 2022
1,945
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.21 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class TopDownPlayer : MonoBehaviour
  6. {
  7.     public float speed = 3f;
  8.  
  9.     private Rigidbody2D rb;
  10.     private Animator animator;
  11.     private SpriteRenderer sp;
  12.  
  13.     private Vector2 moveDirection, lastMoveDirection;
  14.  
  15.     // Start is called before the first frame update
  16.     void Start()
  17.     {
  18.         rb = GetComponent<Rigidbody2D>();
  19.         animator = GetComponent<Animator>();
  20.         sp = GetComponent<SpriteRenderer>();
  21.     }
  22.  
  23.     // Update is called once per frame
  24.     void Update()
  25.     {
  26.         moveDirection.x = Input.GetAxisRaw(Constants.HorizontalInput);
  27.         moveDirection.y = Input.GetAxisRaw(Constants.VerticalInput);
  28.  
  29.         moveDirection = moveDirection.normalized;
  30.  
  31.         animator.SetFloat("Speed", rb.velocity.sqrMagnitude);
  32.  
  33.         if (moveDirection.sqrMagnitude > 0f)
  34.         {
  35.             lastMoveDirection = moveDirection;
  36.         }
  37.  
  38.         animator.SetFloat("X", lastMoveDirection.x);
  39.         animator.SetFloat("Y", lastMoveDirection.y);
  40.         sp.flipX = lastMoveDirection.x < 0f;
  41.     }
  42.  
  43.     private void FixedUpdate()
  44.     {
  45.         rb.velocity = moveDirection * speed;
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement