#Add Forces to a Rigidbody while already being moved with forces

1 messages · Page 1 of 1 (latest)

lime glen
#

Hi everyone. I am a new developer and I am trying to learn Unity. I recently coded my topdown character movement, moving him with rb.linearVelocity

I also have a PlayerManager script that check colliders when colliding and decrease health or kill him:
I want to add knockback when he collide with an Enemy. The only problem is that if the force is being applied every physic frame with fixedUpdate it wont work, unless i deactivate input, but is not what i want.

Any idea or help?

#

private Vector2 knockbackVelocity;
private float knockbackDuration;
private float knockbackTimer;

if (knockbackTimer > 0)
{
rb.linearVelocity = knockbackVelocity;
knockbackTimer -= Time.fixedDeltaTime;
}
dont consider those lines

clear wind
#

!code

fickle ridgeBOT
clear wind
#
        else
        {
            // Sennò sta fermo
            rb.linearVelocity = Vector2.zero;
        }

there's your answer as to why it isn't working

lime glen
#

So, removing that makes my char sliding.

#

from sec 3 i am not even pressing any keybind

clear wind
#

you could add some linear drag or friction to dampen that, but that'd also reduce your speed

#

you could also disable the movement code for some duration of the knockback

lime glen
#

would you code movement in a different way? maybe i could rework the enire movement code but i dont know if that is better

clear wind
#

i have some variables for state, and while stunned i don't allow input movement

lime glen
#

private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Enemy"))
        {
            TakeHit(other.gameObject.GetComponent<IDamager>().Damage);
            if (health <= 0)
            {
                Die();
            }
            else
            {
                StartCoroutine(Knockback(other));
            }
        }
    }

    IEnumerator Knockback(Collision2D other)
    {
        Vector2 direction = transform.position - other.transform.position;
        
        movement.isKnockback = true;
        rb.AddForce(direction.normalized * knockback, ForceMode2D.Impulse);
        yield return new WaitForSeconds(knockbackTime);
        movement.isKnockback = false;
    }

i "managed" to fix it by adding a Coroutine like this

acoustic arch
lime glen
#

it is a topdown game

acoustic arch
# lime glen it is a topdown game

you're making good progress and figuring out what does and doesn't make sense to model with physics

usually, for arcade style top down games, like Hotline Miami, physics is not used to drive the character

lime glen
#

so i would just move the char with transform?

clear wind
#

if you aren't using a rigidbody, sure

#

but rigidbodies definitely help a lot with making collision detection easy, so not sure why you'd opt out of that

lime glen
#

does colliders need rigidbodies?

clear wind
#

dynamic rigidbodies drive collision, colliders don't really do much if you don't have any rbs

#

unless you're using them for sweepcollider checks i suppose

acoustic arch
# lime glen so i would just move the char with transform?

so because i haven't made that kind of game, i don't really know what to recommend. what i would do is look at this asset - https://topdown-engine.moremountains.com - and see what they did. you don't have to use the asset, but their thinking process was, "what is correct for the genre of game that people are trying to implement"

clear wind
acoustic arch
acoustic arch
# lime glen so i would just move the char with transform?

let's talk about what is really going on

there's a feel for controls that players like in top down shooters. the controls were defined by console & arcade games (GTA 1) that predated physics frameworks + scene graph engines like unity.

none of these games were made with naturalistic physics engines like the one in Unity. sometimes people call these games arcade physics games.

in Unity, it's really convenient to express your game rules, like not being able to move into walls and jumping or whatever, with naturalistic physics

#

the hard part of making this is you want to be able to define walls using 3d colliders, but you want movement that works like gta 1

#

when you try to use the physics forces to recreate GTA 1 character movement, things don't work well. all the emergent behavior of using the physics engine for movement doesn't occur in GTA 1. GTA 1 they don't have a naturalistic physics engine

#

@lime glen does this make sense?

lime glen
#

Yeah, so using only transform would make me going inside colliders maybe?

acoustic arch
#

that's what the more mountains top down asset does. they carefully set everything up so that you can define walls using 3d colliders, but the movement feels like GTA 1

acoustic arch
lime glen
#

is there a way i can look at moremountains games code so that i can learn from those?

acoustic arch
#

like i can go and download the top down engine for you and say how they did things, i'm pretty sure they compute the momentum every frame at "the right time", then they check if any collissions occurred after the physics simulation, and then they reconcile the physics consequences with the user input consequences to calculate a new momentum.

acoustic arch
#

almost all of the solutions involve treating the physics and player inputs in phases

#

the important thing is you are trying all these things and figuring it out

lime glen
#

mhh. Since i still am new i wont spend money. But maybe i can work around decompiling already top down existing games?

acoustic arch
lime glen
#

or some itch.io simple games to see how they handle that

acoustic arch
#

the people i know who are best at this already "see" games like GTA1 on a frame by frame basis, and then they sort of intuitively write code that looks like

inside the execution orderl loop

gather the user's input so far
apply the physics forces to model the input

allow physics to execute

look at what happened according to physics. if i am colliding agains ta wall, for example, use that.

reconcile player inputs and update transforms.

acoustic arch
#

i mean this is why GTA makes a bajillion dollars lol

lime glen
#

i didnt thought it was that hard to just handle a character moving and apply forces while moving lol

acoustic arch
#

yeah it turns out ot be ridiculously hard in Unity

#

like why use unity if you aren't going to use Physics

#

another POV is, this is why people say they like making these retro feeling games in other engines, but then, because they're using something with product development measured in the hundreds of thousands of dollars instead of billions, they never ship a game

lime glen
#

yeah, then i should use gamemaker or something like that if I want to move stuff without physics

#

ideally

acoustic arch
#

the reason you want to use unity is so that you can attach a collider to an object, and now your character can't move into it

#

versus say gamemaker, where you can only not move into things that are tiles that are impassable

#

big difference

lime glen
#

yeah

acoustic arch
#

it's all these emergent behaviors

#

you can look at Rival (unity dots character controller)

lime glen
#

i guess i'll try to find a way to handle multiple physics at the same time

acoustic arch
#

actually you could very well just use it as your top down game character controller and learn a LOT

lime glen
#

i will look at that now i guess

lime glen
#

is it for a 2D game?

acoustic arch
#

the way this character controller works, if you model your game on the xz plane, it will feel right

#

so just from reading these docs, i've learned that the ECS framework (you should think of ECS as Unity 2.0) is flexible enough taht you can implement your own kind of physics object. so imagine if rigidbody had an abstract base class called PhysicsObject, this implements physicsobject.

clear wind
#

charactercontroller is decidedly for 3d

acoustic arch
#

whereas the way to achieve that in unity with kinematic rigidbodies is a lot more cantanerkous. it's not at all impossible. that's what the moremountains asset does

lime glen
#

i know that this is only for this case and not for everything but i could work around like with a function that

takes a force as argument

add that to another rb.velocity

after a time (in the argument)

slide back to rb.velocity

acoustic arch
#

you have to start thinking in terms of the execution order of scripts, which gives you some control over when unity physics versus your own code runs

#

and how to reconcile what the user asked to do

lime glen
#

ok i think i understood the problem. Now'll try to work around that so that i can find a fix

#

thx for the heko