将旋转添加到移动的刚体对象

时间:2018-06-18 02:22:31

标签: unity3d 3d

我正在使用操纵杆移动我的播放器并附加了刚体组件。当玩家移动时,我希望它相应地在Y轴上旋转。例如。如果玩家向右移动,它应该在Y轴上旋转一定程度。

请注意我的游戏是othorgraphic视图中的玩家,这就是为什么移动是基于相机正确移动的原因。

    void FixedUpdate()
{
    Vector3 moveVector = (transform.right * joystick.Horizontal + transform.forward * joystick.Vertical).normalized;
    Vector3 relativeMovement = Camera.main.transform.TransformVector(moveVector);
    rb.AddForce(relativeMovement * speed);
    relativeMovement.y = 0;

如果需要,我的操纵杆代码。

    using UnityEngine;
    using UnityEngine.EventSystems;

     public class FloatingJoystick : Joystick
   {
       Vector2 joystickCenter = Vector2.zero;

public bool joyStickWorking = false;
public bool playerMoving = false;

void Start()
{
    background.gameObject.SetActive(false);
}

public override void OnDrag(PointerEventData eventData)
{
    Vector2 direction = eventData.position - joystickCenter;
    inputVector = (direction.magnitude > background.sizeDelta.x / 2f) ? direction.normalized : direction / (background.sizeDelta.x / 2f);
    handle.anchoredPosition = (inputVector * background.sizeDelta.x / 2f) * handleLimit;
    playerMoving = true;
}

public override void OnPointerDown(PointerEventData eventData)
{
    background.gameObject.SetActive(true);
    background.position = eventData.position;
    handle.anchoredPosition = Vector2.zero;
    joystickCenter = eventData.position;
    joyStickWorking = true;
}

public override void OnPointerUp(PointerEventData eventData)
{
    background.gameObject.SetActive(false);
    inputVector = Vector2.zero;
    joyStickWorking = false;
    playerMoving = false;
}
}

1 个答案:

答案 0 :(得分:0)

尝试使用AddTorque()进行物理旋转 - https://docs.unity3d.com/ScriptReference/Rigidbody.AddTorque.html