c# - 如何在 Unity 中向前移动一个对象?
问题描述
我制作了一个游戏对象并附加了一个脚本。我需要旋转并沿直线移动对象,具体取决于旋转。我转了个弯,但我的运动有问题。有什么解决办法吗?
//Rotation
if (Input.GetAxis("Rotation") > 0) {
transform.Rotate(Vector3.back, turnSpeed * Time.deltaTime);
}
else if (Input.GetAxis("Rotation") < 0)
{
transform.Rotate(Vector3.back, -turnSpeed * Time.deltaTime);
}
//Velocity
if (Input.GetAxis("Thrust") != 0) {
rb.AddForce(Vector3.forward * Time.deltaTime * Speed);
}
else if (Input.GetAxis("Thrust") <= 0.1f){
rb.velocity = new Vector2(0, 0);
}
解决方案
Rigidbody.AddForce
应用向量作为世界空间中的力。因此,您需要给它一个向量,该向量位于变换前向的世界空间方向。幸运的是,这就像使用transform.forward
, transform.up
, ortransform.right
或其中一个的否定而不是Vector3.forward
:
//Rotation
if (Input.GetAxis("Rotation") > 0) {
transform.Rotate(Vector3.back, turnSpeed * Time.deltaTime);
}
else if (Input.GetAxis("Rotation") < 0)
{
transform.Rotate(Vector3.back, -turnSpeed * Time.deltaTime);
}
//Velocity
if (Input.GetAxis("Thrust") != 0) {
Vector3 frontDirection;
// probably one of these for a 2D game:
frontDirection = transform.right;
//frontDirection = -transform.right;
//frontDirection = transform.up;
//frontDirection = -transform.up;
rb.AddForce(frontDirection * Time.deltaTime * Speed);
}
else if (Input.GetAxis("Thrust") <= 0.1f){
rb.velocity = new Vector2(0, 0);
}
推荐阅读
- mysql - Spring JPA 和 MySQL 存储不正确的 LocalDateTime 值
- swift - 如何导航到新视图但删除它与 NavigationView 的连接?
- c# - ATAPI.dll MakeCall 导致 ObjectDisposedException
- python - Roblox 从目录中购买商品
- directus - 如何通过 SQL 查询上传图像?
- android - Android Kotlin listview 适配器过滤器仅显示第一项
- c# - C#中的HTTP持久连接
- ruby-on-rails - 在 Rails 邮件模板中使用 link_to 创建的链接不可点击
- visual-studio-code - 从悬停在 VSCode 扩展中打开另一个文档
- colors - 如何在虚幻中从搅拌机重新创建材质