[英]Using RigidBody2D in Unity
我和我的小伙伴最近聯手打造了一款俯視太空射擊游戲,就像小行星一樣。 我們看過很多教程,我們已經設法使用translate.Transform()
並讓我們的對象移動。
現在我們想使用RigidBody2D
對我們的船施加力:
這是我們 Unity 窗口的屏幕截圖:
如上面的屏幕截圖所示,我們制作了一個帶有飛船精靈、圓形碰撞器、剛體 2D 和 PlayerThrust 腳本的 Player Ship 預制件。
在Thrust.cs
:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Thrust : MonoBehaviour
{
// Thrust script components
public Rigidbody2D rigidBody; // GameObject's Rigidbody2D component
public float thrustAmount; // amount of thrust applied to be defined in unity
private float thrustInput; // float variable to keep track of user input of the 'up' arrow key/'up' axis tilt on joystick
// Start is called before the first frame update
void Start() {}
// Update is called once per frame
void Update()
{
// handle input
thrustInput = Input.GetAxis("Vertical"); // float ranging from -1.0 to +1.0
// Debug
Debug.Log(Vector2.up * thrustInput * thrustAmount);
}
// Fixed Update is called every fixed framerate frame
// use for physics
void FixedUpdate() {
// only accelerate forward
if (thrustInput > 0)
{
// Apply thrust in direction ship is facing
rigidBody.AddRelativeForce(transform.up * thrustInput * thrustAmount);
}
}
}
為什么船不動?
Debug.Log(Vector2.up * thrustInput * thrustAmount);
輸出一個有意義的數字,當按下↑按鈕時它會上升到推力量,並在釋放按鈕時返回到 0.0。
這是一個測試,看看發生了什么。 2個腳本。 一個將產生一艘船(一個立方體),另一個將使用推進器。 按住向上鍵一點以接合推進器,因為立方體快速下落。
這應該至少適用於 Unity 5.6 到 2020 年。
#1 -
創建一個新的空白場景。 確保您處於 2D 視圖中。 不要改變任何東西。 將此腳本添加到相機(它所做的只是生成一個對象):
using System.Collections;
using UnityEngine;
public class SpawnShipTest : MonoBehaviour
{
private void Start()
{
//Create a new scene, put this script on your camera.
StartCoroutine(SpawnTestObject());
}
IEnumerator SpawnTestObject()
{
//Spawn object
var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
var col = go.GetComponent<BoxCollider>();
Component.Destroy(col);
yield return new WaitForSeconds(.2f);
go.transform.position = new Vector3(0f, 0f, -2f);
go.AddComponent<ShipThrustTest>();
go.AddComponent<Rigidbody2D>();
}
}
#2 -
將此腳本添加到您的項目文件夾中的某處(然后按播放,並查看游戲窗口):
using UnityEngine;
public class ShipThrustTest: MonoBehaviour
{
// Thrust script components
public Rigidbody2D rigidBody;
public float thrustAmount; // amount of thrust applied to be defined in unity
private float thrustInput; // float variable to keep track of user input of the 'up' arrow key/'up' axis tilt on joystick
void Start()
{
rigidBody = GetComponent<Rigidbody2D>();
thrustAmount = 10f;
}
void Update()
{
thrustInput = Input.GetAxis("Vertical");
}
void FixedUpdate()
{
if (thrustInput > 0)
{
rigidBody.AddRelativeForce(transform.up * thrustInput * thrustAmount * 2f, ForceMode2D.Force);
}
}
}
謝謝您的幫助。
主要的錯誤是我們將Rigidbody2D
與 3-D 對象一起使用,而不僅僅是Rigidbody
...我們對游戲是“2-D”游戲這一事實感到困惑,即使我們的資產是 3 維的.
我們也從未想過使用rigidBody = GetComponent<Rigidbody2D>();
或使用參數, ForceMode2D.Force
。 這些都是很好的提示。 很棒的測試腳本@Kale_Surfer_Dude!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.