#Enemy movement with velocity

1 messages · Page 1 of 1 (latest)

limber tapir
#

You can set the velocity directly by assigning to the rigidbody's velocity property
https://docs.unity3d.com/ScriptReference/Rigidbody2D-velocity.html

Your math is actually set up to calculate velocity but it is being applied as a force which won't actually give you movement matching the value in the speed variable. You can use what is currently called force as the velocity and sit it every frame inside the isGrounded check.

When the enemy is not grounded, you'll want to calculate movement velocity and it's velocity from gravity. you can use acceleration * time to calculate that and use whatever acceleration value makes sense for the game. If you want to match what the physics engine is already doing, it should be set to -9.81 which is Earth's acceleration due to gravity.

You can add the two velocities together to get the correct velocity for when an enemy is falling and apply that to the rigidbody whenever the enemy isn't grounded.

#

just remember the velocity from falling would accumulate, so it would be something like
fallSpeeed += accelerationFromGravity * deltaTime

pure prairie
#

I'm a little confused

#

This is what I have so far

#
// Movement
        if (isGrounded)
        {
            rb.velocity = force * Time.fixedDeltaTime;
            Debug.Log("Pushed");
            Debug.Log("Force = " + force);
        }
        else
        {
            rb.velocity = force * gravity * Time.fixedDeltaTime;
        }
limber tapir
#

That seems fairly correct though without all the code it would be difficult to say if it will work

pure prairie
limber tapir
#

What is the value of speed?

#

It was probably very small before since it was being used as a force. You can now use it as a true velocity in world units

pure prairie
limber tapir
#

ah sorry!

#

your velocity for movement should not be using deltaTime.

#

the only place where you would need deltaTime would be for calculating the portion of velocity from gravity, since that velocity will accumulate.

pure prairie
limber tapir
#

100 is probably far too high

#

it will be moving 100 units a second

#

you'll want a more reasonable move speed. The up side of taking this approach is whatever speed you set is exactly the speed they will move, which will be a bit easier to design around.

When falling, it may be easier to calculate your velocity from game logic and velocity from gravity separately, since only one of those will need delta time (gravityVelocity = acceleration * time)

pure prairie
#

It now falls very slowly and keeps twitching while moving towards the player when its on the ground