簡體   English   中英

在 Unity 2d 中跳躍

[英]Jumping in Unity 2d

我弄清楚了左右移動的東西,但我似乎無法讓我的玩家跳躍。 我有代碼,但我不斷收到一條錯誤消息,提示“尚未分配 Player.controller 的變量 Player。”

這是代碼:

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

public class Player_controller : MonoBehaviour
{
    public float speed;
    // Start is called before the first frame update
    void Start()
    {
        
    }
    public Rigidbody2D Player;
    float JumpHeight = 10f;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.D))
        {
            Debug.Log("Moving Right");

            transform.Translate(Vector3.right * Time.deltaTime * speed);
        }

        if (Input.GetKey(KeyCode.A))
        {
            Debug.Log("Moving Left");

            transform.Translate(Vector3.left * Time.deltaTime * speed);
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("Jumping");

            Player.AddForce(Vector2.up * JumpHeight, ForceMode2D.Impulse);
        }    
    }
}

如果玩家有一個剛體組件,你可以在Awake()方法中引用它。 如果沒有,只需添加組件

private void Awake() {
    Player = GetComponent<Rigidbody2D>();
}

或者只是將剛體組件拖到檢查器中的插槽

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM