简体   繁体   English

在C#unity中将速度添加到2d精灵

[英]Adding velocity to 2d sprite in c# unity

hi i was wondering if someone could help me fix practice code (i make practice codes before i make the real thing because its just how i roll) it is basically an object that requires the user to click on the screen in order for it to not touch the ground much like flappy bird however although i have applied gravity correctly to the sprite i cannot fix the velocity section (i coded is to every time the user clicks with his mouse or taps the space key the object will move up like flappy bird) 您好,我想知道是否有人可以帮助我修复练习代码(我在制作真实的东西之前先制作练习代码,因为它就是我的滚动方式),它基本上是一个对象,需要用户单击屏幕才能使其不就像拍打飞鸟一样触地,但是尽管我已经正确地将重力施加到了精灵上,但是我无法固定速度部分(我编码是每次用户用鼠标单击或敲击空格键时对象都会像拍打飞鸟一样向上移动)

using UnityEngine;
using System.Collections;

public class BirdMovment : MonoBehaviour {

    Vector3 Velocity = Vector3.zero;
    public Vector3 gravity;
    public Vector3 flapVelocity;
    public float maxSpeed = 5f; 

    bool didFlap = false;

    // Use this for initialization
    void Start () {

    }

    void update (){
        if (Input.GetKeyDown (KeyCode.Mouse0)) 
        {
            didFlap = true; 
        }
    }

    // Update is called once per frame
    void FixedUpdate () {
        Velocity += gravity* Time.deltaTime;

        if (didFlap) {
            didFlap = false;
            Velocity += flapVelocity;

        }
        Velocity = Vector3.ClampMagnitude (Velocity, maxSpeed);

        transform.position += Velocity * Time.deltaTime;
    }
}

can you please fix the error as every time i set the velocity in unity for the sprite ad run the program the sprite just keeps on falling and no matter how much i click or tap the space key the sprite does not stop falling even if i increase the velocity 您能否解决错误,因为每次我为Sprite广告运行程序统一设置速度时,Sprite都会不断下降,无论我单击或轻击空格键多少,Sprite都不会停止下降,即使我增加速度

First of all, the correct Update function is with a capital U, so Update() instead of update() . 首先,正确的Update函数使用大写字母U,因此使用Update()而不是update() Then, since you're not doing anything with physics, you can do everything in Update and not use FixedUpdate at all. 然后,由于您没有对物理学做任何事情,因此可以在Update进行所有操作,而完全不使用FixedUpdate So you can remove the didFlap variable and add to Velocity directly inside the if (Input.GetKeyDown ...) block. 因此,您可以删除didFlap变量并直接在if (Input.GetKeyDown ...)块内添加到Velocity Furthermore, regarding gravity, you're multiplying it twice with Time.deltaTime there, so remove the first one. 此外,关于重力,您要将其与Time.deltaTime乘以两次,因此删除第一个。 That should get you started. 那应该让您开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM