Move it! Physics movement and the constantly loop

Knowledgebase / Move it! Physics movement and the constantly loop

We’re going to make a game object move towards the mouse. This tutorial follows on from Hello, world! Displaying text.

Step 1: The Constantly event loop

Right-click on Newton, and select Edit script.

Open the Events tab, and drag out the Constantly block. This block will constantly trigger the blocks inside it (over and over and over again while the game is running.



Step 2: The “set velocity” block

Open the Physics tab and grab the “Set velocity x 0” block. Drag this block inside the Constantly block.



This block gives velocity (speed) to the object. Velocity x means horizontal speed. Velocity x 0 means it has zero horizontal speed, so it stays still.

Click on the 0 and type in 100 instead. Click Play to see your object move in the game.

Instead of setting the object’s x velocity to 0 or 100, we’ll set the velocity to the distance between the mouse and the object. The further away the mouse is, the bigger the distance will be, making the object travel faster towards the mouse. When the difference is 0, the object’s velocity will be 0.


Step 3: The subtraction block

Open the Operators tab and grab the “( ) + ( )” block. Drag this block on top of the 100, and the 100 should pop out. Drag the 100 into the trash can on the bottom-right.



This is the addition block for adding numbers together, but we’re going to change it to the subtraction block. Click on the + and select the – to change it into a subtraction block.



Step 4: The position of the mouse minus the position of myself

Open the Sensing tab and grab the “x position of the mouse + camera x” block. Drag it into the left side of the subtraction block. This block gives us the position of the mouse anywhere in the game.


Then open the Transform tab and grab the “x position of myself” block. Drag it into the right side of the subtraction block. This block gives us the position of this object.


Click Play to test it out. Notice how the object only moves on the x-axis (horizontally).


Step 5: Repeat for setting y velocity

Click Edit to return to editing your script. Now right-click on the “set velocity x” block, and select Duplicate. Drag the duplicated block underneath the original one.



To make the object also follow the mouse vertically, we need to set its y velocity. On the duplicated blocks, click on the x and change them to y.



Now play your game again to test it out. Your object now speeds towards the mouse!

Don’t forget to save your game.