How to set a variable to the nearest multiple

Monkey Forums/Monkey Programming/How to set a variable to the nearest multiple

mteo77(Posted 2013) [#1]
Hello everybody.
I was wondering how is the best way to set a variable to the nearest multiple of another variable.
I will describe the scenario that is giving me troubles...
I am making a grid based game, where all the actors can move in every direction on a 32*32 grid; the actors can move on the grid in a fluid motion, but they are restricted by the amount they can move each turn (hope i described it properly).
When an actor gets shot it freeze in place.
The problem is, if actor 1 shoots actor 2, the collision can happen when actor 2 is still moving, so actor 2 will freeze in mid air...
Is there a way to tell actor 2 that when shot it's position has to be the nearest multiple of 32?
I tried to put an extra condition in the collision detection function (like "check collision only if actor is not moving") but the check , due to the speed of the bullets, can be skipped entirely if the collision happen when the actor has just moved, and by the time the 32 pixel movement stops, the bullet has gone past the actor detection zone (hope i made it clear).
So i thought it would be much easier to check for collision and replace the collided actor in the nearest grid (i haven't actually implemented a grid class, i just make the movements step by step).


GfK(Posted 2013) [#2]
probably something like:
x = x - (x Mod 32)



Midimaster(Posted 2013) [#3]
It sounds like the actors are moving automatic from one grid to the next...
And it sound like you would like to have, that the actor should continue the move it makes at this moment.

So create a property flag of the actor "WillBeDead%" and set it to TRUE, when the actor is shoot. Next time, when the actor reaches its grid position, stop the movement.



Another idea is to move it quickly the rest of the way to the next grid position:
TargetX=(ActorX+SpeedX*32) Mod 32
DiffX=TargetX-ActorX
ActorX= ActorX + DiffX

TargetY=(ActorY+SpeedY*32) Mod 32
DiffY=TargetY-ActorY
ActorY= ActorY + DiffY



Gerry Quinn(Posted 2013) [#4]
Edit, I made a hames of my calculations, of course the standard method is simply x -= x Mod 32. However, the method described below still works:


Since 32 is a power of two, you can use the following bit of trickery instead:

x = ( x + 16 ) & $FFFFFFE0


It runs fast and works for positive or negative values of x, but it does depend on x being an integer.

$FFFFFFE0 is how -32 is written in hexadecimal. By doing a bitwise and operation with it, you chop off the least significant binary digits of the result, i.e. 16/8/4/2/1, which for integers is the same as a sign-independent mod 32.


mteo77(Posted 2013) [#5]
Thanks!
I tried using mod and it worked, but i haven't thought about giving it an extra flag.
Ill try both solutions and see which one gives the better results.
Thank you Gfk and Midimaster.