I have an enemy that moves towards the player.
I have the usual set up with DX, DY, X, Y. Where X and Y are the co-ordinates of enemy, DX & DY are the direction of movement.
I thought it would be good to have it set up like this:
e.dx and e.dy are the enemies dx and dy.
e.x and e.y are the enemies x and y cords.
plyr.x and plyr.y are the players co-ords...
If the plyr.x MINUS the enemy.x is a positive sign in the result, move the dx 1 or right.
If the plyr.x MINUS the enemy.x is a negative sign in the result, move the dx negative 1 or left.
If the plyr.y, minus 2 (so the enemy is slightly higher) MINUS the enemy.y is a positive sign in the result, move the dy 1 or down.
If the plyr.y, minus 2 (so the enemy is slightly higher) MINUS the enemy.y is a negative sign in the result, move the dy -1 or up.
This works very well and I was pleased with myself for shortening the code.
However, my problem is (especially on the y) that if the enemy and the player are the same y value, the enemy wiggles up and down and the sign of the maths goes -1,1,-1,1,-1,1,-1 etc...
I seem to remember there's something I'm missing to stop the enemy 'vibrating' like this when the coodinates are the same but can't remember what it is.
Would someone please help as I'm a bit lost.
Honestly, I would just use my own implementation of sign(), since I'm really not sure why the pico-8 one doesn't return 0 in that case. However, if you want to do the minimum amount of code to get what you've got to work, I think this expression would work:
the part in the parentheses would then become either 2 or -2 if the x values are different and 0 if they're the same.
As per kimiyoribaka's suggestion, you can just redefine sgn so you shouldn't even need to change your existing code. This should do the trick.
function sgn(n) return n==0 and 0 or abs(n)/n end
If you have code tokens to spare, I think an If statement with Abs() is more clear, and you can adjust the threshold and speed nicely
dy = plyr.y-2 - e.y if (abs(dy) >= 1) then --threshold of 1, could change e.dy = 1 * sgn(dy) --speed of 1, could change else e.dy = 0 endif
[Please log in to post a comment]