Why GameObject in Unity starts moving when i add rigidbody and only rotate it in script

huangapple go评论90阅读模式
英文:

Why GameObject in Unity starts moving when i add rigidbody and only rotate it in script

问题

在添加刚体(Rigidbody)组件后,游戏对象开始朝前方移动的原因是什么?

使用 UnityEngine;

public class PlayerMover : MonoBehaviour
{
    private Vector2 _mouseInput;
    private Vector2 _rotation;

    private void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    private void Update()
    {
        CalculateRotation();

        transform.rotation = Quaternion.Euler(_rotation.x, _rotation.y, 0);
    }

    private void CalculateRotation()
    {
        _mouseInput.x = Input.GetAxisRaw("Mouse X");
        _mouseInput.y = Input.GetAxisRaw("Mouse Y");

        _rotation.y += _mouseInput.x;
        _rotation.x -= _mouseInput.y;
    }
}
英文:

I rotate GameObject by moving mouse, when i added rigidbody GameObject started moving in forward direction, why does it move?

using UnityEngine;

public class PlayerMover : MonoBehaviour
{
private Vector2 _mouseInput;
private Vector2 _rotation;

private void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
}

private void Update()
{
    CalculateRotation();

    transform.rotation = Quaternion.Euler(_rotation.x, _rotation.y, 0);
}

private void CalculateRotation()
{
    _mouseInput.x = Input.GetAxisRaw("Mouse X");
    _mouseInput.y = Input.GetAxisRaw("Mouse Y");

    _rotation.y += _mouseInput.x;
    _rotation.x -= _mouseInput.y;
}
}

答案1

得分: 0

添加一个刚体组件到一个物体将把它的运动交由Unity的物理引擎控制。即使不添加任何代码,一个带有刚体组件的物体将会受到重力的作用并且会对撞击它的物体做出反应,前提是合适的碰撞器组件也存在。

这回答了你的问题吗?老实说,如果你仅仅阅读文档,你会发现,给一个游戏对象添加刚体就像赋予它真实世界的特性(重力、运动、力等)。

英文:

RigidBody and I quote

> Adding a Rigidbody component to an object will put its motion under the control of Unity's 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 right Collider component is also present.

Does this unswer you question ? to be honest if you just read the documentation you'll find out , adding rigidbody to a gameobject is like giving an object the features of real-life (gravity , movement , force etc).

huangapple
  • 本文由 发表于 2023年3月7日 21:38:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662707.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定