# code is right but i dont understant how its working

• October 30th, 2012, 11:52 PM
hwoarang69
code is right but i dont understant how its working
this code works find. all its doing is setting collsion around enemy. and if player touch player from right than player move to right. if player touch enemy from left than player move to left.

playerX = player x postion
playerY = player y postion
playerW = player width
playerH = player height
x = enemy x postion
y - enemy y postion
width - enemy width
height - enemy height
p.setX = set player x postion
...

Code :

```if(playerX + playerW >= x && playerX <= x + width) { if(playerY+playerH >= y && playerY <= y+height) { if (playerX <= x) //player on left { System.out.println(playerX +"--"+x); p.setX(x - width); } else if(playerX >= x)//player on right { p.setX(x + width); } } }```

this code below i understand how its working
Code :

```if(playerX + playerW >= x && playerX <= x + width) { if(playerY+playerH >= y && playerY <= y+height) {```

but this code is like magic!
ok so if player x postion is on left of enemy x, than move player to right
Code :

``` if (playerX <= x) //player on left p.setX(x - width);```

but i dont get it. bc if want to to see if player is on left of enemy than i should take playerX+playerW so collsion point is on right of player head. for ex.
Code :

` if (playerX+playerW <= x) //thsi i understand but its not right why??`
and next line shoud be enemy x - player width.
Code :

`p.setX(x - playerW) //this i understand but its not right. why??`

i was thinking if playerx+playerW will get me a point at right of player head. and
this will test if player right side of head is <= enemy x(which is left of enemy head)
if (playerX+playerW <= x) //this shoudl work.........
• October 31st, 2012, 12:22 AM
jps
Re: code is right but i dont understant how its working
if (playerX+playerW <= x) //this shoudl work.........

Time for some trouble shooting then.
You make multiple assumptions and something does not work the way you wanted, odds are something is not quite right.
Do some printlns on the variables each step. Follow what the code does. This is a great learning opportunity. Figure out why it is working the way it does when you use: if (playerX+playerW <= x) and figure out what would have to be done to make it work the way you expected it to work. If you dig deep enough there is a treasure chest.