所以我做了一個球(玩家),它自己用腳本向前移動。我想讓那個球像一個普通的球一樣。當它豐富平臺邊緣時,它不會脫落。基本上它停在邊緣。這是我的圖片:

這是我的控制器腳本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwerveInputSystem : MonoBehaviour
{
private float _lastFrameFingerPositionX;
private float _moveFactorX;
public float MoveFactorX => _moveFactorX;
void Start(){
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
_lastFrameFingerPositionX = Input.mousePosition.x;
}
else if (Input.GetMouseButton(0))
{
_moveFactorX = Input.mousePosition.x - _lastFrameFingerPositionX;
_lastFrameFingerPositionX = Input.mousePosition.x;
}
else if (Input.GetMouseButtonUp(0))
{
_moveFactorX = 0f;
}
}
}
這是第二個腳本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour{
private SwerveInputSystem _swerveInputSystem;
[SerializeField] private float swerveSpeed = 5f;
[SerializeField] private float maxSwerveAmount = 1f;
[SerializeField] private float verticalSpeed;
void Start(){
_swerveInputSystem = GetComponent<SwerveInputSystem>();
}
void Update(){
float swerveAmount = Time.deltaTime * swerveSpeed * _swerveInputSystem.MoveFactorX;
swerveAmount = Mathf.Clamp(swerveAmount, -maxSwerveAmount, maxSwerveAmount);
transform.Translate(swerveAmount, 0, 0);
float verticalDelta = verticalSpeed * Time.deltaTime;
transform.Translate(swerveAmount, verticalDelta, 0.1f);
}
}
uj5u.com熱心網友回復:
您Rigidbody沒有受到影響的一個可能原因是gravity該欄位isKinematic被選中。從Rigidbody檔案中,切換時isKinematic,
力、碰撞或關節將不再影響剛體。通過更改transform.position,剛體將處于影片或腳本控制的完全控制之下
當gravity檢查此設定時,就像一個力量,沒有力量在物件上行動,當它不再在平臺上時,您的物件將不會下降。一個簡單的解決方案是取消選中此框。
uj5u.com熱心網友回復:
編輯:調整了答案,因為我們現在有一些源代碼。
您直接定位播放器(使用其變換),這會弄亂物理。剛體的目的是讓 Unity 為您計算力、重力等。當您使用物理并且想要移動物件時,您有三個主要選項:
將物體傳送到新位置,忽略碰撞體和重力等力。在這種情況下,使用剛體的位置屬性。
_ourRigidbody.position = new Vector3(x, y, z);將物體移動到新位置,類似于傳送,但移動可以被其他碰撞器打斷。因此,如果物件和新位置之間有墻,則移動將在墻處停止。使用MovePosition()。
_ourRigidbody.MovePosition(new Vector3(x, y, z));向物件添加一些力并讓物理引擎計算物件的移動方式。有幾個選項,如AddForce()和AddExplostionForce()等......有關更多資訊,請參閱Rigidbody組件。
_ourRigidbody.AddRelativeForce(new Vector3(x, y, z));
在您的情況下,您可以簡單地洗掉 transsform.Translate() 呼叫,而是添加一些像這樣的力:
//transform.Translate(swerveAmount, 0, 0);
//transform.Translate(swerveAmount, verticalDelta, 0.1f);
Vector3 force = new Vector3(swerveAmount, verticalDelta, 0);
_ourRigidbody.AddForce(force);
我們可以照常在 Awake() 或 Start() 方法中獲取 _ourRigidbody 變數。正如你所看到的,我喜歡Assert檢查只是為了安全,有一天有人會錯誤地移除剛體,然后很高興知道它......
private SwerveInputSystem _swerveInputSystem;
private Rigidbody _ourRigidbody;
void Start()
{
_swerveInputSystem = GetComponent<SwerveInputSystem>();
Assert.IsNotNull(_swerveInputSystem);
_ourRigidbody = GetComponent<Rigidbody>();
Assert.IsNotNull(_ourRigidbody);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324772.html
標籤:统一3d
下一篇:使用C#在Unity中物件太快
