Untitled

 avatar
unknown
csharp
4 years ago
1.4 kB
35
Indexable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterControls : MonoBehaviour
{
    Rigidbody2D rb2d;
    public float speed = 200f;
    public float jumpForce = 200f;

    int jumpInput;
    float moveInput;

    bool isGrounded = false;
    float checkRadius = 0.5f;
    public Transform groundCheck;
    public LayerMask groundMask;
    
    Quaternion facingRight = Quaternion.Euler(Vector3.zero);
    Quaternion facingLeft = Quaternion.Euler(new Vector3(0, 180, 0));
    

    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        moveInput = Input.GetAxisRaw("Horizontal");

        isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, groundMask);
        if (Input.GetButtonDown("Jump") && isGrounded) {
            jumpInput = 1;
        } else {
            jumpInput = 0;
        }

        // left-right sprite flip
        if (moveInput > 0) {
            transform.rotation = facingRight;
        }
        if (moveInput < 0) {
            transform.rotation = facingLeft;
        }
    }

    private void FixedUpdate() {
        // vertical movement
        rb2d.velocity = new Vector2(moveInput * speed * Time.deltaTime, rb2d.velocity.y);
        // jumping
        rb2d.AddForce(new Vector2(0, jumpInput * jumpForce * Time.deltaTime), ForceMode2D.Impulse);

    }

}
Editor is loading...