TransWikia.com

How to make Rigidbody.AddForce less delayed in Unity3D?

Game Development Asked on January 5, 2022

I’m trying to make it so that when the player in my game moves left or right, he lightly jumps from his current position to his new position. The way I have it set up now, the jump occurs once he has arrived at his new position. What can I do to make it so that the jump happens sooner so that it appears that he jumps to his new position? Here is the code I have that controls that part of his movement:

if (Input.GetKeyDown(KeyCode.LeftArrow) && transform.position.x > minXPos)
    {
        targetPos = new Vector3(transform.position.x - xIncrement, transform.position.y, transform.position.z);
        rb.AddForce(Vector3.up * jumpForceTwo, ForceMode.Impulse);
        transform.position = Vector3.MoveTowards(targetPos, transform.position, speed);
        isHorizontalingLeft = true;
    }
else if (Input.GetKeyDown(KeyCode.RightArrow) && transform.position.x < maxXPos)
    {
        targetPos = new Vector3(transform.position.x + xIncrement, transform.position.y, transform.position.z);
        rb.AddForce(Vector3.up * jumpForceTwo, ForceMode.Impulse);
        transform.position = Vector3.MoveTowards(targetPos, transform.position, speed);
        isHorizontalingRight = true;
    }

Here is a video showing what is happening (sorry it’s blurry):
https://youtu.be/rPewtb8QywE

One Answer

I can't tell from a video when you're applying input, but it looks to me like your problem is not that the jump is delayed, but rather that your character teleports instantly instead of moving over a period of time.

Your code moves the player like this:

transform.position = Vector3.MoveTowards(targetPos, transform.position, speed);

I am assuming your code takes place in an Update() function. You are not accounting for Time.deltaTime here, so your character may be moving 60x faster than you expect. Normally your speed should be in units per second and you should multiply speed by Time.deltaTime like this:

transform.position = Vector3.MoveTowards(targetPos, transform.position, speed * Time.deltaTime);

This way your movement speed is consistent regardless of framerate. For example, if the speed is 10 and a frame lasts 1/60th of a second, the actual distance moved in one frame would be 10 * (1 / 60) = .16667. If the game stuttered during the next frame and the frame lasted 2/60ths of a second, the distance moved for that frame would be 10 * (2 / 60) = .333333

Answered by Kevin on January 5, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP