我對 Unity 和 C# 很陌生。我已經知道 python,所以 C# 很容易掌握,但現在我遇到了一個問題。我無法運行此代碼。它導致出現錯誤。我檢查了很多次代碼,但找不到問題。這是代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb2D;
private float moveSpeed;
private float moveHorizontal;
private float moveVertical;
// Start is called before the first frame update
void Start()
{
moveSpeed = 3f;
rb2D = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
}
void FixedUpdate()
{
moveHorizontal = Input.GetAxisRaw("Horizontal");
if (moveHorizontal > 0.1f || moveHorizontal < -0.1f)
{
rb2D.AddForce(new Vector2(moveHorizontal * moveSpeed), ForceMode2D.Impulse);
}
}
}
地板(白色矩形)是一個剛體和盒子碰撞器。玩家也是如此(紅色方塊)。我想用鍵盤移動方塊。
任何幫助將不勝感激
uj5u.com熱心網友回復:
問題在這里:
rb2D.AddForce(new Vector2(moveHorizontal * moveSpeed), ForceMode2D.Impulse);
Vector2 將 2 個浮點數作為輸入。要修復它,你必須這樣做
new Vector2(moveHorizontal * moveSpeed, moveVertical * moveSpeed)
您忘記在 vector2 中定義垂直運動
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/461604.html
下一篇:返回列表