Unity Rigidbody使用 之 获取运动物体的速率
来源:网络收集 点击: 时间:2024-04-19Rigidbody:
Control of an objects position through physics simulation.
Adding a Rigidbody component to an object will put its motion under the control of Unitys physics engine. Even without adding any code, a Rigidbody object will be pulled downward by gravity and will react to collisions with incoming objects if the rightCollidercomponent is also present.The Rigidbody also has a scripting API that lets you apply forces to the object and control it in a physically realistic way. For example, a cars behaviour can be specified in terms of the forces applied by the wheels. Given this information, the physics engine can handle most other aspects of the cars motion, so it will accelerate realistically and respond correctly to collisions.
2/4Rigidbody.velocity:
1)功能描述
publicVector3velocity;
The velocity vector of the rigidbody.
In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour. Dont set the velocity of an object every physics step, this will lead to unrealistic physics simulation. A typical example where you would change the velocity is when jumping in a first person shooter, because you want an immediate change in velocity.
using UnityEngine;using System.Collections;2)使用案例public class ExampleClass : MonoBehaviour {
public Rigidbody rb;
void Start() {
rb = GetComponentRigidbody();
}
void FixedUpdate() {
if (Input.GetButtonDown(Jump))
rb.velocity = new Vector3(0, 10, 0);
}
}
3/4Vector3.magnitude:
public floatmagnitude;
Returns the length of this vector (Read Only).
The length of the vector is square root of(x*x+y*y+z*z).If you only need to compare magnitudes of some vectors, you can compare squared magnitudes of them usingsqrMagnitude(computing squared magnitudes is faster).
4/4方法提示:
1)获取物体Rigidbody组件
2)Rigidbody.AddForce给物体施加力
3)求得物体的Rigidbody.velocity.magnitude,并打印
二、Rigidbody使用 之 获取运动物体的速率1/8打开Unity,新建一个空工程,具体如下图

在场景中,新建“Plane”和“Cube”,并调整他们你的布局,具体如下图

在工程中新建一个脚本“VelocityTest”,双击脚本或者右键“Open C# Project”打开脚本,具体如下图

在打开的脚本“VelocityTest”上编辑代码,首先获取物体“Rigidbody”组件,然后在Update函数中按下“F”键给物体施力,最后求得物体的“Rigidbody.velocity.magnitude”,并打印,具体的代码和代码说明如下图

“VelocityTest”脚本的具体内容如下:
usingUnityEngine;
publicclassVelocityTest:MonoBehaviour{
privateRigidbodyrigidbody;
publicfloatsmooth=50.0f;
//Usethisforinitialization
voidStart(){
rigidbody=this.transform.GetComponentRigidbody();
}
//Updateiscalledonceperframe
voidUpdate(){
if(Input.GetKeyDown(KeyCode.F)){
rigidbody.AddForce(Vector3.right*smooth);
}
floatspeed=rigidbody.velocity.magnitude;
print(speed:+speed);
}
}
6/8脚本编译正确,回到Unity,把脚本“VelocityTest”赋给“Cube”,并给“Cube”添加“Rigidbody”组件,具体如下图

运行场景,按下“F”键,即可看到物体运动,控制台console打印对应速率数据,具体如下图

到此,《Unity Rigidbody使用 之 获取运动物体的速率》讲解结束,谢谢
注意事项为了好的实验效果,可以适当调整“Rigidbody”的参数值
您的支持,是我们不断坚持知识分享的动力,若帮到您,还请帮忙投票有得;若有疑问,请留言
UNITYRIGIDBODYVELOCITY获取物体速率版权声明:
1、本文系转载,版权归原作者所有,旨在传递信息,不代表看本站的观点和立场。
2、本站仅提供信息发布平台,不承担相关法律责任。
3、若侵犯您的版权或隐私,请联系本站管理员删除。
4、文章链接:http://www.1haoku.cn/art_546427.html