Advertisement
Guest User

Unity PlayerController 2D

a guest
Oct 5th, 2016
2,245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.50 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class PlayerController : MonoBehaviour {
  5.  
  6.     private float xInput, yInput;
  7.     public int speed = 1;
  8.     private Rigidbody2D body;
  9.     public Animator animator;
  10.     private bool isMoving;
  11.  
  12.  
  13.     // Use this for initialization
  14.     void Start () {
  15.         body = GetComponent<Rigidbody2D>();
  16.         animator = GetComponent<Animator>();
  17.         isMoving = false;
  18.         // isAttacking = false;
  19.     }
  20.    
  21.     // Update is called once per frame
  22.     void Update () {
  23.  
  24.         // Attack Test
  25.         if(Input.GetButtonDown("Fire1"))
  26.         {
  27.             animator.SetTrigger("Attack");
  28.         }
  29.  
  30.         // Get input
  31.         xInput = Input.GetAxisRaw("Horizontal");
  32.         yInput = Input.GetAxisRaw("Vertical");
  33.  
  34.         // If IsMoving, Move with 3d Vector
  35.         isMoving = (xInput != 0 || yInput != 0);
  36.  
  37.         if (isMoving)
  38.         {
  39.             var moveVector = new Vector3(xInput , yInput, 0);  
  40.  
  41.             // BAD MOVEMENT - Circumvents RigidBody2D Physics
  42.             // transform.position += moveVector * speed * Time.deltaTime;
  43.             //
  44.  
  45.             // CORRECT MOVEMENT
  46.             body.MovePosition(new Vector2((transform.position.x + moveVector.x * speed * Time.deltaTime),
  47.                    transform.position.y + moveVector.y * speed * Time.deltaTime));
  48.  
  49.  
  50.             animator.SetFloat("xInput", xInput);
  51.             animator.SetFloat("yInput", yInput);
  52.         }
  53.  
  54.         animator.SetBool("isMoving", isMoving);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement