# How to make an object oscillate left and right?

I can't seem to make an object move left and right, back and forth, on room start whilst on solid ground.

Codes I used:

Step Event:

if image_index is greater than 5, then physics_apply_force (0,0,100,0) for the right

if image_index is less than 5, then physics_apply_force (0,0,-100,0) for the left

• What's wrong with the way you're doing it now?
– House
Dec 28, 2014 at 18:53
• When I apply these codes on room start, the movement speeds are different from each other (left/right). And the object keeps shifting on it's own, even though I have set it in a certain position in the room. Dec 28, 2014 at 18:57
• If you're wanting multiple objects to be synced, perhaps using physics forces isn't the best idea? Is this a Space Invaders type enemy movement? What else have you tried?
– House
Dec 28, 2014 at 19:02
• It's a platform game. The object is for a moving object (like an enemy) in the room. A bit like a moving mushroom in mario, but left and right? Dec 28, 2014 at 19:18

It sounds like you desire Simple Harmonic Motion; if so, you must apply a force proportional to, but of opposite sign from, the displacement from the origin of the motion to have it be stable.

That is to say, apply a force with components Fx = - c * x and Fy = - d * y.

• Would you be able to make a small example file for me? It's sounds complicated. I am very new to physics in general. Dec 28, 2014 at 19:42
• @NicoleGamer: I don't do programming that uses a physics engine; the games I write don't require one. I am merely a physicist who programs (mostly business applications) and occasionally visits this site to provide guidance on the mathematical and physical foundations of game programming. Dec 28, 2014 at 19:48
• ^^ I don't know "game-maker" but it looks like it would be something like // f = 100 // physics_apply_force(0,0,(image_index - 5) * -f,0) // where f is how tight the spring is. Dec 28, 2014 at 20:14
• Yes like a spring could be away to do it. Is it possible for an example? Dec 29, 2014 at 18:28

I have received help from a person on Youtube. He gave me an example, showing the code to be phy_speed_x=-10 for the object to move left or phy_speed_x=+10 to move right, whilst using physics. I was using the wrong code all along!

I don't understand what you're trying to do, but if you want an object to move back and forth somewhere in your room, you could multiply that object SpeedX variable by -1 in whatever Event you want it to bounce, this way it will invert its horizontal speed and make it go the other way.

• Yes, but in physics mode you can't set the horizontal speed like normal. I have tried, it just doesn't work. The only code that seems to work for movement in physics mode is the physics_apply_force code. I am still having trouble getting the speeds synced for both left and right, when object is moving. Dec 28, 2014 at 20:24