1

Hi guys.
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.

 ```e.dx=sgn(plyr.x-e.x) e.dy=sgn((plyr.y-2)-e.y)```

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.

Cheers.

P#97940 2021-09-28 22:25

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:

 `e.dx=(sgn(plyr.x-e.x)-sgn(e.x-plyr.x))/2`

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.

P#97945 2021-09-28 23:42
1

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```
P#97966 2021-09-29 09:26

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

pseudo-code...

 ```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```
P#97980 2021-09-29 15:01

Thank you one and all.
I went with jasondelaat's solution in the end.
I didn't know you could redefine 'built in' functions!

Again, many thanks.

P#97987 2021-09-29 16:31