【问题标题】:Unity Acceleration & Deceleration C#Unity 加速和减速 C#
【发布时间】:2018-08-22 00:43:19
【问题描述】:

我对 Unity 和 C# 还很陌生,一直在努力解决这个问题!

我希望我的飞船逐渐加快速度,然后像没有重力一样缓慢停止,因为这将是一场太空游戏!

如果有人可以帮助我,甚至指导我学习这个主题的教程,我将不胜感激! :)

这是我目前宇宙飞船的代码...

using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;

public class PlayerMovement : MonoBehaviour {

    public float maxSpeed = 6f;
    public float rotSpeed = 180f;


    void Start ()
    {

    }

    void Update () {
        Quaternion rot = transform.rotation;

        float z = rot.eulerAngles.z;

        z -= CrossPlatformInputManager.GetAxis ("Horizontal") * rotSpeed * Time.deltaTime;

        rot = Quaternion.Euler (0, 0, z);

        transform.rotation = rot;

        Vector3 pos = transform.position;

        Vector3 velocity = new Vector3 (0, CrossPlatformInputManager.GetAxis("Vertical") * maxSpeed * Time.deltaTime, 0);

        pos += rot * velocity;

        transform.position = pos;


    }
}

如何做到这一点?

【问题讨论】:

  • 所以你想做一些“easeInOutCubic”吗? (取自 CSS)
  • 也许this 可以帮助你在不使用物理引擎的情况下实现你想要的(即使我猜在你的情况下使用物理更容易)。

标签: c# unity3d


【解决方案1】:

与 Unity 中的任何东西一样,有一百种方法可以做到这一点,但我认为使用物理是最简单的。

现在您正在直接操作转换。这很好,但实际上比让 Unitys 物理为您做数学要复杂得多。

您需要做的就是将一个刚体组件(或用于 2D 游戏的 Rigidbody2D)附加到您的飞船上。

然后,通过向 Rigidbody 施加力,您将获得一个不错的逐渐加速,并且通过在 Inspector 中调整 Rigidbody 的线性和角度拖动,您将获得非常平滑和自然的减速感觉。

这里是使用物理的官方文档:https://docs.unity3d.com/Manual/class-Rigidbody.html

利用物理是 Unity 开发中非常有趣且重要的一部分,所以如果您刚刚开始,我强烈建议您现在学习它,这是用它解决的完美问题。

【讨论】:

    【解决方案2】:

    你可以试试这个:

    Vector3 velocity = transform.forward * CrossPlatformInputManager.GetAxis("Vertical") * maxSpeed * Time.deltaTime;
    
    pos += velocity;
    
    transform.position = pos;
    

    我希望它有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      相关资源
      最近更新 更多