简体   繁体   中英

How Can I Gradually Add More Force To An Object To Increase It's Speed Regardless of It's Direction?

I'm new in Unity. I am trying to make a 2D game similar to Pong. However, I want to increase more speed to Ball over time to make it harder. I set the gravity scale of the Ball to zero so that it doesn't fall down. I added a force and bouncy Physics element to the ball. So it bounces back from walls and it goes to different directions.

Here is a screenshot of Game I'm working on: 在此处输入图像描述

MY QUESTION IS:

  • How can I add more force to the ball regardless of which direction it bounces back?

<Note: I tried putting it inside FixedUpdate () method but the ball goes crazy because of constantly executing same function every frame. I was thinking of adding more force to the ball over time by using InvokeRepeating ( ) method later on to set time interval. If there is better idea of using other techniques, giving me a little advice will help me a lot> Thank you !

I would recommend using a Coroutine or an InvokeRepeating . I would also recommend changing your code a bit.

rbBall.AddForce(rbBall.transform.right * ballForce)

The above snippet will add the ballForce in the direction the rbBall is moving.

Now for the two example snippets.

Coroutine

private float timeBeforeAddForce = 5f;

private void Start()
{
    StartCoroutine(GradualAddForceToBall());
}

private IEnumerator GradualAddForceToBall()
{
    // wait for 5 seconds
    yield return new WaitForSeconds(timeBeforeAddForce);
    
    // add the speed
    rbBall.AddForce(rbBall.transform.right * ballForce)
    
    // call the coroutine again
    StartCoroutine(GradualAddForceToBall());
}

InvokeRepeating

private void Start()
{
    InvokeRepeating("GradualAddForceToBall", 0.0f, timeBeforeAddForce);
}

private void GradualAddForceToBall()
{
     rbBall.AddForce(rbBall.transform.right * ballForce)
}

If you want to change the current time of how long the speed is applied, I would go with the Coroutine as you can gradually decrease the timeBeforeAddingForce every time it enters the Coroutine .

I found the answer. You can force an object to be a specific speed while keeping its same movement direction - normalize the velocity (which sets the value to have a mangitude of 1) and then multiply it by your desired speed:

Here is the code:

public float currentSpeed = 5f;
void FixedUpdate()
{
    //This will let you adjust the speed of ball using normalization
    rbBall.velocity = rbBall.velocity.normalized * currentSpeed;
}

Adjust the currentSpeed variable to change it's speed. ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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