GMS 2 Moving Object Collision

Hi - I have two blocks moving at a speed of 1 toward each other.

One at a speed of 1 and the other -1 (x += dir)

I am trying to make them bounce off each other (reverse direction) with the following code:

Code:
if  place_meeting(x+dir,y,o_solid){
    if dir = -1{dir = 1;}else{dir = 1;}       
}

x += dir;
Except the first object to hit will change direction, meaning the second one will stay the same direction because the first is no longer colliding (so they both end up going the same way, next to each other).

Any ideas on how I can solve this?
 

chamaeleon

Member
Any ideas on how I can solve this?
Have the code also modify the colliding instance, or have a control object whose purpose is to control all moving blocks. In any case, nothing stops you from changing the instance variables of another instance at the same time as the current instance. Just need to be careful that you don't do something "twice".
 
Have the code also modify the colliding instance, or have a control object whose purpose is to control all moving blocks. In any case, nothing stops you from changing the instance variables of another instance at the same time as the current instance. Just need to be careful that you don't do something "twice".
I know what you mean, and have tried this. However my 2 objects are the same object - so even id I change code of the id, both are running the code.
 

chamaeleon

Member
I know what you mean, and have tried this. However my 2 objects are the same object - so even id I change code of the id, both are running the code.
Same object is fine and very common. Just use something like instance_position instead of place_meeting to find out which instance you are colliding with, and change both as needed. If the other instance then runs the same code you either have moved the instances apart so that it doesn't trigger or otherwise keep track of the fact that you have handled the collision already by some other means (instance variables, or some other state management).
 
Got it working. Turns out I needed to change the '1' to a '-1'

if dir = -1{dir = 1;}else{dir = -1;}

Then I could add the colliding object code and it works fine.

Final code:
Code:
if  place_meeting(x,y,o_solid){

    var type = instance_place(x,y,o_solid);
    if type.dir = -1{type.dir = 1;}else{type.dir = -1;}
    if dir = -1{dir = 1;}else{dir = -1;}
}

x += dir;
 

Sabnock

Member
this is a classic example of why you should use hspd and vspd.

if you have a collision that you want to reverse simply multiply hspd or vspd by -1;
 
Top