如何在Unity中让火箭绕其底部而非中间轴心旋转?

3

我该如何让火箭播放器控制器围绕其底部旋转?

以下是我的代码(我知道它有问题,现在只是概念验证):

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rocket : MonoBehaviour
{
    Rigidbody rigidBody;
    void Start()
    {
        rigidBody = GetComponent<Rigidbody>();
    }

    void Update()
    {
        ProcessInput();
    }

    private void ProcessInput()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            rigidBody.AddRelativeForce(Vector3.up);
        }

        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            if (!Input.GetKey(KeyCode.D) && !Input.GetKey(KeyCode.RightArrow))
            {
                transform.Rotate(new Vector3(0, 0, 2));
            }
        }

        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            if (!Input.GetKey(KeyCode.A) && !Input.GetKey(KeyCode.LeftArrow))
            {
                transform.Rotate(new Vector3(0, 0, -2));
            }
        }
    }
}

1
最好在谷歌上搜索“unity更改枢轴点”,而不是在那里创建一个全新的问题... - Alexey Larionov
2个回答

3

好消息,Unity有:Transform.Rotate

更加实用的是:Transform.RotateAround

我很确定这正是你想要的。

顺便提一下 - 要弄清楚你要绕旋转的向量不是那么简单。你必须对叉积和其它矢量操作有很好的感觉。Unity就是这样让人恼火——一开始它看起来很容易使用,但你真的需要对牛顿力学、每个方面的矢量和四元数有非常出色的掌握才能制作游戏——这很困难。

一个提示:你看到如何添加力来移动它。试着添加扭矩 (AddTorque) 来旋转它!


谢谢!这正是我在寻找的! - Yuval Amir
1
小心使用这些!您不应该通过“Transform”组件将物理(Rigidbody)与任何变换混合在一起,因为这会破坏物理和碰撞检测,并且通常表现出奇怪的行为。 - derHugo
1
没错!注意回答中的最后一句话,@YuvalAmir - Fattie

0
如果您有一个 Rigidbody,请不要通过 transform 混合运动!这会破坏物理和碰撞检测,并导致奇怪的行为。

最好使用例如{{link1:Rigidbody.centerOfMass}}根据您的需求设置质心。

然后使用{{link2:AddTorque}}或{{link3:MoveRotation}}。

private void ProcessInput()
{
    if (Input.GetKey(KeyCode.Space))
    {
        rigidBody.AddRelativeForce(Vector3.up);
    }

    if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
    {
        if (!Input.GetKey(KeyCode.D) && !Input.GetKey(KeyCode.RightArrow))
        {
            turnLeft = true;
        }
    }

    if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
    {
        if (!Input.GetKey(KeyCode.A) && !Input.GetKey(KeyCode.LeftArrow))
        {
            turnRight = true;
        }
    }
}

private bool turnLeft;
private bool turnRight;

private void FixedUpdate ()
{
    if(turnLeft)
    {
        turnLeft = false;
        rigidbody.MoveRotation(rigidBody.MoveRotation(rigidbody.rotation * Quaternion.Euler(0, 0, 2));
    }

    if(turnRight)
    {
        turnRight = false;
        rigidBody.MoveRotation(rigidBody.MoveRotation(rigidbody.rotation * Quaternion.Euler(0, 0, -2));
    }
}

虽然一般来说,使用每秒角度(例如)更容易。

rigidBody.MoveRotation(rigidbody.rotation * Quaternion.Euler(0, 0, -45 * Time.deltaTime));

Time.deltaTime 是自上一次物理更新以来经过的时间,因此这可以确保您每秒旋转 -45°


或者您可以查看如何更改对象的中心点 -> 您可以将网格放在父对象下,然后使用该父对象作为刚体和移动脚本等,以便您可以创建任何相对于父对象的偏移量。

是的,您也可以自己重新计算网格顶点位置以适应您的需求,但通常使用父子关系的方法已经足够了 ;)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接