코드

참고로 Player에 Constant Force 컴포넌트를 달아주고, y축 Force를 -25 정도로 설정해줘야 잘 작동한다. 발밑에 땅이 있는 경우에만 점프하는 메커니즘은;

2024.03.10 - [Unity] - [Unity] 플레이어와 발판이 같이 움직이게 만들기

 

[Unity] 플레이어와 발판이 같이 움직이게 만들기

서론초창기 때 아무것도 모르고 transform.localScale = new Vector2(-4, 4); 이런 식으로 플레이어가 바라보는 방향을 바꿨었기에, Player가 MovingPlatform 위에 있을 때, 이를 따라가게 만들려면 엄청난 공을 들

quickclid.tistory.com

윗글에서 GroundSensor 부분을 참고하면 된다.

using UnityEngine;

public class Player : MonoBehaviour
{
    private Rigidbody rb;

    private float speed;
    private Vector3 accDirection;
    private float velDamp;
    private float jumpForce;

    private void Awake()
    {
        rb = GetComponent<Rigidbody>();

        speed = 200;
        accDirection = Vector3.zero;
        velDamp = 0.75f;
        jumpForce = 750;
    }

    private void FixedUpdate()
    {
        rb.linearVelocity += accDirection * speed * Time.fixedDeltaTime;
        rb.linearVelocity = new Vector3(rb.linearVelocity.x * velDamp, rb.linearVelocity.y, rb.linearVelocity.z * velDamp);
    }

    private void Update()
    {
        Move();
        Jump();
        Sneak();
    }

    private void Move()
    {
        accDirection = Vector3.zero;
        if (Input.GetKey(KeyCode.D)) accDirection += Vector3.right;
        if (Input.GetKey(KeyCode.A)) accDirection += Vector3.left;
        if (Input.GetKey(KeyCode.W)) accDirection += Vector3.forward;
        if (Input.GetKey(KeyCode.S)) accDirection += Vector3.back;
        accDirection = accDirection.normalized;
    }

    private void Jump()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0, rb.linearVelocity.z);
            rb.AddForce(Vector3.up * jumpForce);
        }
    }

    private void Sneak()
    {
        if (Input.GetKeyDown(KeyCode.LeftShift))
        {
            speed = 50;
            return;
        }
        if (Input.GetKeyUp(KeyCode.LeftShift))
        {
            speed = 200;
            return;
        }
    }
}

 

+ Recent posts