- Home /
Adding a velocity to a rigid body inst working.
Hi guys,
Iam creating a simple game. I have problem with my enemy behaviour. When a player attack an enemy, enemy shoud have some knockback. For this Iam using simple rb.velocity = new Vector2D(x ,y). It is interesting that it works only on y cordinate. The enemy just jump (move on y cordinate), but never moves on x cordinate.
Do you know where do I make mistake?
Thanks
private void Knockback()
{
knockbackStartTime = Time.time;
rb.velocity = new Vector2(knockbackSpeed.x, knockbackSpeed.y);
Debug.Log(knockbackSpeed);
//Check time for knockback
if (Time.time >= knockbackStartTime + knockBackDuration)
{
state = State.run;
}
}
This picture is RigidBody on enemy
Answer by Captain_Pineapple · Jul 23, 2020 at 02:02 PM
I guess that the knockback does not work well together with the way you move your enemy. If you also set a velocity there it cancels out the knockback.
But from why you postet it's not possible to tell that for sure. It's just an assumption since your code as is seems to be ok.
For moving I am using $$anonymous$$oveTowards function.
private void $$anonymous$$ove()
{
state = State.run;
Vector2 targetPosition = new Vector2(target.position.x, transform.position.y);
transform.position = Vector2.$$anonymous$$oveTowards(transform.position, targetPosition, speed * Time.deltaTime);
}
targetPosition is position of Player.
well there you have the issue. If you want to use pyhsics and velocity then you have to stick to that system or design a "hybrid-system" that does hard movement of the enemies and takes their velocity into account.
So for example you could remove the rigidbody and give your Script it's own velocity vector. There you can then add knockback and movementvelocitys as you like and then move the enemy accordingly.
Your current system just overwrites the velocity you set by a hard movement countering the knockback.