团结 - 向左或向右转动时倾斜飞船

时间:2017-07-22 11:04:10

标签: c# unity3d

目前我有一艘飞行在行星周围的宇宙飞船。看起来像这样

enter image description here

我使用此代码

public class PlayerMovement : MonoBehaviour
{
    private float currentMovementSpeed = 30;
    private float rotationSpeed = 80;
    private Rigidbody rigid;

    private void Start()
    {
        rigid = GetComponent<Rigidbody>();
    }

    private void Update()
    {
        // move the spaceship
        rigid.MovePosition(rigid.position + transform.TransformDirection(new Vector3(0, 0, 1)) * currentMovementSpeed * Time.deltaTime);

        // rotate the shaceship by pressing A or D
        transform.Rotate(0, Input.GetAxis(StringCollection.INPUT_HORIZONTAL) * rotationSpeed * Time.deltaTime, 0);
    }
}

所以,当我按A时,我想把船向左倾斜

enter image description here

当按D时我想向右侧倾斜

enter image description here

有人知道该怎么做吗?

2 个答案:

答案 0 :(得分:2)

而不是:

transform.Rotate(0, Input.GetAxis(StringCollection.INPUT_HORIZONTAL) * rotationSpeed * Time.deltaTime, 0);

你应该使用这样的东西:

 rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);

以下是使用它的示例:

using UnityEngine;
using System.Collections;

[System.Serializable]
public class Boundary
{
    public float xMin, xMax, zMin, zMax;
}

public class PlayerController : MonoBehaviour
{
    public float speed;
    public float tilt;
    public Boundary boundary;

    void FixedUpdate ()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
        rigidbody.velocity = movement * speed;

        rigidbody.position = new Vector3 
        (
            Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax), 
            0.0f, 
            Mathf.Clamp (rigidbody.position.z, boundary.zMin, boundary.zMax)
        );

        rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);
    }
}

您可能有兴趣观看以下教程,因为它与您尝试创建的内容类似:

https://unity3d.com/es/earn/tutorials/projects/space-shooter/moving-the-player?playlist=17147

答案 1 :(得分:0)

你也可以查看这个资产 - 所有的代码都被评论过,而且非常流畅 - 对我帮助很大。

基本上,它有一个非常通用的脚本来执行基于LERP的凸轮跟随船。这有点像普通的平滑跟随,除了你完全3D,所以船可以完全颠倒等。控制很容易改变,我自己做,但默认是船不断移动并使用箭头键进行俯仰/偏航。

这里有一个主要想法 - 你有一个childed相机目标物体,相机使用LERPing跟随它 - 给出一个非常有趣的访问/减速效果:

// lerp the camera back to its correct position
    _cam.transform.localPosition = Vector3.Lerp(_cam.transform.localPosition, _camTarget.transform.localPosition, 1f - CameraLag);
    _cam.transform.localRotation = Quaternion.Lerp(_cam.transform.localRotation, _camTarget.transform.localRotation, 1f - CameraLag);

https://assetstore.unity.com/packages/3d/vehicles/space/low-poly-space-ship-ultra-smooth-360-controller-111640