[英]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.