Answers for "2d player movement code c#"

C#
5

unity 2d c# movement

//This is not a Plataformer type movement 
//Its more of like the old pokemon games type movement if you know what im talking about
//Body Type on RigidBody 2D must be set to kinematic
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
    Rigidbody2D body;

    float horizontal;
    float vertical;

    public float runSpeed = 10.0f;


    // Start is called before the first frame update
    void Start()
    {
        body = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");
        vertical = Input.GetAxisRaw("Vertical");
    }

    private void FixedUpdate()
    {
        body.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);
    }
}
Posted by: Guest on June-17-2021
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, turnRight;
    [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.GetAxis("Horizontal");
    }
    void FixedUpdate(){
        if (isGround && Input.GetKey(KeyCode.Space))
        {
            rb.velocity = Vector2.up * jumpForce * Time.deltaTime;
        }
        rb.velocity = new Vector2(input * speed * Time.deltaTime, rb.velocity.y);
        if (turnRight && input > 0){
            Flip();
        }
        else if (!turnRight && input < 0){
            Flip();
        }
    }
    void Flip(){
        turnRight = !turnRight;
        Vector3 Scale = transform.localScale;
        Scale.x *= -1;
        transform.localScale = Scale;
    }
}
Posted by: Guest on September-04-2021

C# Answers by Framework

Browse Popular Code Answers by Language