0
\$\begingroup\$

I'm fairly new to creating a 2D game in java and I'd love some help. I'm trying to create a sort of knock back effect the enemies have on you. So when you are touched by a enemy you will:

  1. lose life

  2. be knocked back a few pixels

I thought about saying something simple such as:

    if ((player.x & player.y) == (enemy.x & enemy.y)){  
        player.x += 8;
        player.y += 8;
    }

But seeing as this will only push you back with no hope of moving while being pushed, I didn't want to use it. Is there any simple, yet effective way for going about this?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ If you can, adding a velocity component, and adding/subtracting to/from the velocity would help facilitate a more realistic knockback. \$\endgroup\$ Commented Dec 11, 2013 at 1:31
  • 1
    \$\begingroup\$ It could be my unfamiliarity with Java, but the conditional there looks dicey to me. I think what you want is "if(player.x == enemy.x && player.y == enemy.y)" The bitwise-and operators in the version you've shown could lead to some unexpected false positives. \$\endgroup\$ Commented Dec 11, 2013 at 17:19

1 Answer 1

3
\$\begingroup\$

Usually this is done by changing velocity.

If you simply change position, there is danger of stucking in walls (and other solid objects, including enemises) or falling/jumping through them (depends on your collision system and level design).

Also you need to configure friction and/or gravity accordingly, so player will not fly into open space after one kick.

If inertial sliding will be too smooth for you, some engines allowing to attach short-living constant-power pushing forces to objects.

Honestly, it is hard to answer without knowing anything about your physics engine and its capabilities.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.