问题描述
我有一个游戏对象,我想确定该对象是向上移动(正向)还是向下移动(负向).我该怎么做?
假定对象具有刚体,则可以在附着到GameObject的MonoBehavior的更新方法(或任何与此相关的方法)中使用它.
我有一个游戏对象,我想确定该对象是向上移动(正向)还是向下移动(负向).我该怎么做?
假定对象具有刚体,则可以在附着到GameObject的MonoBehavior的更新方法(或任何与此相关的方法)中使用它.
Rigidbody rb = GetComponent<Rigidbody>();
float verticalVelocity = rb.velocity.y;
如果要沿任何轴移动速度,可以使用点积:
Rigidbody rb = GetComponent<Rigidbody>();
Vector3 someAxisInWorldSpace = transform.forward;
float velocityAlongAxis = Vector3.Dot(rb.velocity, someAxisInWorldSpace);
上面的代码将为您提供沿GameObject的向前轴的速度(向前速度).
如果对象没有刚体,则可以将其旧位置保存在变量中,然后将其与更新循环中的当前位置进行比较.
Vector3 oldPosition;
private void Start() {
oldPosition = transform.position;
}
private void Update() {
Vector3 velocity = transform.position - oldPosition;
float verticalVelocity = velocity.y / Time.deltaTime; // Divide by dt to get m/s
oldPosition = transform.position;
}
I have a gameobject and I would like to find out if the object is moving upward (positive) or downward (negative). How do I get to do this?
Assuming that the object has a rigidbody, you can use this in the update method (or anywhere for that matter) of a MonoBehavior attached to your GameObject.
Rigidbody rb = GetComponent<Rigidbody>();
float verticalVelocity = rb.velocity.y;
If you want the velocity along any axis, you can use the dot product:
Rigidbody rb = GetComponent<Rigidbody>();
Vector3 someAxisInWorldSpace = transform.forward;
float velocityAlongAxis = Vector3.Dot(rb.velocity, someAxisInWorldSpace);
The above code would give you the velocity along the GameObject's forward axis (the forward velocity).
If the object doesn't have a rigidbody, you can save its old position in a variable and then compare it to the current position in the update loop.
Vector3 oldPosition;
private void Start() {
oldPosition = transform.position;
}
private void Update() {
Vector3 velocity = transform.position - oldPosition;
float verticalVelocity = velocity.y / Time.deltaTime; // Divide by dt to get m/s
oldPosition = transform.position;
}
这篇关于如何知道物体是向上移动还是向下移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!