Answers for "2d character movement unity"

C#
0

2d player movement unity

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

public class PlayerMovement : MonoBehaviour
{
    [Header("Player Movement")]
    private Rigidbody2D rb;
    [SerializeField] private float speed, jumpForce, checkRadius;
    private float input;
    [SerializeField] private Transform groundCheck;
    private bool isGround;
    [SerializeField] private LayerMask groundLayerMask;
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        isGround = Physics2D.OverlapCircle(groundCheck.position, checkRadius, groundLayerMask);
        input = Input.GetAxisRaw("Horizontal");
    }
    void FixedUpdate(){
        rb.velocity = new Vector2(input * speed * Time.deltaTime, rb.velocity.y);
        if (isGround && Input.GetKey(KeyCode.Space))
        {
            rb.velocity = Vector2.up * jumpForce * Time.deltaTime;
        }
    }
}
Posted by: Guest on September-04-2021
0

2d Unity Character Movement

public float speed;
    public float jumpForce;
    private float moveInput;

    private Rigidbody2D rb;

    private bool facingRight = true;

    private bool isGrounded;
    public Transform groundCheck;
    public float checkRadius;
    public LayerMask whatIsGround;



    private int extraJumps;
    public int extraJumpValue;



    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        extraJumps = extraJumpValue;
    }

    // Manage all physics related aspects of our game

    void FixedUpdate()
    {

        isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);


        moveInput = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);

        if (facingRight == false && moveInput > 0)
        {
            Flip();
        } else if(facingRight == true && moveInput < 0)
        {
            Flip();
        }

    }

    private void Update()
    {
        if(isGrounded)
        {
            extraJumps = extraJumpValue;
        }
       if (Input.GetKeyDown(KeyCode.UpArrow) && extraJumps > 0) {
            rb.velocity = Vector2.up * jumpForce;
            extraJumps--;
        } else if (Input.GetKeyDown(KeyCode.UpArrow) && extraJumps == 0 && isGrounded)
        {
            rb.velocity = Vector2.up * jumpForce;
        }
    }

    void Flip()
    {
        facingRight = !facingRight;
        Vector3 Scaler = transform.localScale;
        Scaler.x *= -1;
        transform.localScale = Scaler;
    }
Posted by: Guest on November-05-2021

C# Answers by Framework

Browse Popular Code Answers by Language