首页 > 解决方案 > C#:y 轴速度随时间增加

问题描述

所以....我编写了一些代码,当你按下空间并向右增加一个力时,让你的火箭旋转,看起来随着你走得越多,速度就会增加,这是为什么呢?

对不起我的解释,我是统一和编程的初学者所以..不要评判我

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerMovement: MonoBehaviour 
{
    private float gravity;
    public float moveSpeed = 20f;
    private Rigidbody2D rb;
    private Vector2 startPos;
    public Vector2 velocity;
    public static PlayerMovement Instance 
    {
        get;
        set;
    }
    // Start is called before the first frame update
    private void Start() 
    {
        Instance = this;
        startPos = transform.position;
        rb = GetComponent < Rigidbody2D > ();
        gravity = rb.gravityScale;
    }

    // Update is called once per frame
    private void Update() 
    {
        Vector2 vel = rb.velocity;
        float ang = Mathf.Atan2(vel.y, x: 30) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(new Vector3(x: 0, y: 0, z: ang - 90));
        rb.AddForce( - velocity * Time.deltaTime, ForceMode2D.Impulse);
        rb.AddForce(Vector2.right * 500 * Time.deltaTime);

        if (Input.GetKey(KeyCode.Space)) {
            rb.AddForce(Vector2.up * 3000 * gravity * Time.deltaTime);
        }
    }
    void OnCollisionEnter2D(Collision2D col) 
    {
        if (col.gameObject.tag == "Obstacle") 
        {
            Die();
        }
    }
    void Die() 
    {
        SceneManager.LoadScene(0);
    }
}

标签: c#visual-studiounity3d

解决方案


RigidBody.AddForce 是原因,每当您使用它时,它都会为您的游戏对象添加一个力,并且您在每一帧上都这样做。


推荐阅读