“Wie man die Spielerbewegung in Unity 2D macht” Code-Antworten

Bewegung Einheit 2d

// This movement is used for platformer type games
bool jump = false;
float MovementSmoothness = 0.1f;
public float JumpForce;
public PlayerSpeed;
Rigidbody2D rb;

void Start(){
  rb = GetComponent<Rigidbody2D>();
}
void Update()
{
  	horizontal = Input.GetAxisRaw("Horizontal");
  	if(Input.GetKeyDown(KeyCode.W) jump = true;
}

private void FixedUpdate()
{
  	if(jump){
      rb.AddForce(new Vector2(0f, JumpForce));
      jump = false;
    }
  	if(Input.GetKey(KeyCode.LeftShift))// If shift is pressed, sprint
            targetvelocity =  new Vector2(horizontal * PlayerSpeed * 2 * Time.deltaTime, rb.velocity.y);
    else // else go normally
            targetvelocity =  new Vector2(horizonal * PlayerSpeed * Time.deltaTime, rb.velocity.y);
  	// this makes movement much smoother ans satisfying
  	rb.velocity = Vector3.SmoothDamp(rb.velocity,targetvelocity, new Vector3(0,0,0), MovementSmoothness);
}
Xixika

Wie man die Spielerbewegung in Unity 2D macht

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

public class PlayerMovement : MonoBehaviour
{
	// this has jumping, movement, and the code for groundCheck. You must do
    // things yourself in the unity editor to for groundCheck. Code Tested
    // unity 2d platformer
    
    
    public float speed = 5f;
    public float jumpSpeed = 3f;
    private float direction = 0f;
    private Rigidbody2D player;

    public Transform groundCheck;
    public float groundCheckRadius;
    public LayerMask groundLayer;
    private bool isTouchingGround;
    // Start is called before the first frame update
    void Start()
    {
        player = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        isTouchingGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
        direction = Input.GetAxis("Horizontal");

        if (direction > 0f)
        {
            player.velocity = new Vector2(direction * speed, player.velocity.y);
        }
        else if (direction < 0f)
        {
            player.velocity = new Vector2(direction * speed, player.velocity.y);
        }
        else
        {
            player.velocity = new Vector2(0, player.velocity.y);
        }

        if (Input.GetButtonDown("Jump") && isTouchingGround)
        {
            player.velocity = new Vector2(player.velocity.x, jumpSpeed);
        }

    }
}
Prickly Plover

Ähnliche Antworten wie “Wie man die Spielerbewegung in Unity 2D macht”

Fragen ähnlich wie “Wie man die Spielerbewegung in Unity 2D macht”

Weitere verwandte Antworten zu “Wie man die Spielerbewegung in Unity 2D macht” auf C#

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen