【问题标题】:Delay Attaching a gravity in an Object延迟在对象中附加重力
【发布时间】:2021-02-21 03:02:18
【问题描述】:

我有一个可以从左到右移动的球,它还附有重力,会增加加时赛。
问题:我如何将重力附加/添加到对象延迟 3 秒。
期望:在开始时我仍然可以在没有重力的情况下从左到右移动球,所以在 y 轴的相同位置,但 3 秒后球将有重力并开始下落。

public class PlayerController : MonoBehaviour
{
    //Init
    public Vector2 speedMinMax;
    public Vector2 gravityMinMax;
    float speed;
    float move;
    float gravity;
    float halfPlayerWidth;
    private float screenHalfWidthInWorldUnit;
    //Components
    Rigidbody2D rigidbody2D;

    void Awake()
    {
        rigidbody2D = GetComponent<Rigidbody2D>();
    }

    public void Start()
    {
        SpawnPlayer();
        halfPlayerWidth = transform.localScale.x / 2f;
        screenHalfWidthInWorldUnit = Camera.main.aspect * Camera.main.orthographicSize + halfPlayerWidth;
    }

    void Update()
    {
        IncreaseGravity();
        PlayerBounds();
    }

    void FixedUpdate()
    {
        PlayerInput();
    }

    void SpawnPlayer()
    {
        transform.position = new Vector2(0, Camera.main.orthographicSize - transform.localScale.y - 2f);
    }

    void PlayerInput()
    {
        //PlayerInput
        //Keyboard
        speed = Mathf.Lerp(speedMinMax.x, speedMinMax.y, Difficulty.GetDifficultyPercent());
        move = Input.GetAxis("Horizontal");
        rigidbody2D.velocity = new Vector2(move * speed, rigidbody2D.velocity.y);
    }
    
    void IncreaseGravity()
    {
        gravity = Mathf.Lerp(gravityMinMax.x, gravityMinMax.y, Difficulty.GetDifficultyPercent());
        rigidbody2D.gravityScale = gravity;
    }
}

【问题讨论】:

    标签: c# unity3d game-physics game-development


    【解决方案1】:

    RigidBody2D.gravityScale 组件控制附加对象的重力。您可以创建一个协程并将 gravityScale 设置为 0 以禁用。 3 秒后将其设置为旧值或所需值。 `

    IEnumerator WaitForGravity()
     {
         rigidbody2d.gravityScale = 0;
         yield return new WaitForSeconds(3);
         rigidbody2d.gravityScale = 1;
     }
    

    在启动函数时触发这个协程。

    void Start()
    {
        StartCoroutine(WaitForGravity());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多