Solved - Bouncing an enemy

EDIT - Never mind, figured it out. It feels so good to solve a problem on your own :slight_smile:

I am trying to bounce an enemy across walls. However, my code is working as planned.

Here it is -

if (x >= 750) 
		{
			x = 749;
			newDirection = true;
		}
		
		if (x <= 10) 
		{
			x = 11;
			newDirection = true;
		}
		
		if (y == 480) 
		{
			y = 479;
			newDirection = true;
		}
		
		if (y == 10)
		{
			y = 11;
			newDirection = true;
		}
		
		if (newDirection)
		{			
			if ((dx == 1) && (dy == 1))
			{
				if (y == 479) dx = -1;
				if (x == 749) dy = -1;
			}
			
			if ((dx == 1) && (dy == -1))
			{
				if (y == 479) dx = -1;
				if (x == 11) dy = 1;
			}
			
			if ((dx == -1) && (dy == 1))
			{
				if (y == 11) dx = 1;
				if (x == 749) dy = -1;
			}
			
			if ((dx == -1) && (dy == -1))
			{
				if (y == 11) dx = 1;
				if (x == 11) dy = 1;
			}
			newDirection = false;
		}
		
		x = x + dx;
		y = y + dy;

Any help would be appreciated.

Instread of the whole new direction thing just if x<whatever then make dx=-dx to move in the opposite direction

want to offer some tips also:

  • avoid magic nummbers, create some fields or constants which hold such values like your map min max
  • way to much reduant code. everytime u see in your code repeating patters, in moste cases, something is wrong(very bad coding style).
  • try to use more expressiv variable naming

tryed me on a cleaner version, perhaps you find it helpfull


static final int X_MAX = 750;
static final int X_MIN= 10;
static final int X_MAX= 480;
static final int Y_MIN= 10;

int positionX, positionY;
int velocityX, velocityY;

...

void applyVelocity()
{
    positionX += velocityX;
    positionY += velocityY;

    if(isOutsideBorder(X_MIN, X_MAX, positionX))
    {
        positionX = getReflection(velocityX < 0 ? X_MIN : X_MAX, positionX);
        velocityX *= -1;
    }

    if(isOutsideBorder(Y_MIN, Y_MAX, positionY))
    {
        positionY = getReflection(velocityY < 0 ? Y_MIN : Y_MAX, positionY);
        velocityY *= -1;
    }
}

bool isOutsideBorder(int min, int max, value)
{
    return (value> max | value < min);
}

int getReflection(int center, int value)
{
       return 2 * center - value;
}

...

<- ps: don’t like this anyway(have it so un ObjectOrientated), so why not use a 2D array for the data. Makes it extentable for 3D and saves you 11 lines of code.

also a perhaps more OO way


static final Area MAP_AREA= new Area(10, 10, 750, 480);
static final BorderRestriction  RESTRICTION = Reflection;

Vector2 position, velocity;

...

void applyVelocity()
{
    position.add(velocity);
    RESTRICTION.apply(position, velocity, MAP_AREA);
}

..