ProjectAstero 02 – Movement

Hi,

In this video we are going to create movement script for our game,

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Tut_PlayerController : MonoBehaviour
{
    private Rigidbody2D rb2D;
    private float MoveDir;
    private float RotationDirection;
    [SerializeField] private float Acceleration;
    [SerializeField] private float MaxSpeed;
    [SerializeField] private float RotationSpeed;
    private void Start()
    {
        rb2D = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        MoveDir = Input.GetAxis("Vertical"); // -1 or +1
        RotationDirection = Input.GetAxis("Horizontal"); // -1 or +1
    }

    private void FixedUpdate()
    {
        Move();
        Rotate();
    }

    public void Move()
    {
        rb2D.AddForce(transform.up * MoveDir * Acceleration, ForceMode2D.Impulse);
        rb2D.velocity = new Vector2(
            Mathf.Clamp(rb2D.velocity.x, (-1) * MaxSpeed, MaxSpeed),
            Mathf.Clamp(rb2D.velocity.y, (-1) * MaxSpeed, MaxSpeed)
            );
    }

    public void Rotate()
    {
        rb2D.MoveRotation(rb2D.rotation + RotationSpeed * (-1)*RotationDirection);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *