Code for Moving Platform

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ryugomez

Can anyone explain me why this code for the moving platform in Godot demo platformer project works. In fact, that I wonder why the player moves too without even coding for it.

extends Node2D

# Member variables
export var motion = Vector2()
export var cycle = 1.0
var accum = 0.0


func _physics_process(delta):
    accum += delta * (1.0 / cycle) * PI * 2.0
    accum = fmod(accum, PI * 2.0)
    var d = sin(accum)
    var xf = Transform2D()
    xf[2]= motion * d
    $body.transform = xf
:bust_in_silhouette: Reply From: LordViperion

This code modify the transform variable of a object which named is body in from a scenetree. But for me not too clear what is that you re thinking.

I’m sorry, I forgot to mention. Can you explain that code to me line by line?

ryugomez | 2019-02-02 12:38

I mean is that a kind of formula like easing? What kind of equation is that 'cause that looks quite intimidating to me. I’m not just copying and pasting any code without even understanding that they do.

ryugomez | 2019-02-02 13:00

Member variables

// Movement vector define a movedir and a length
export var motion = Vector2()
/Define how many frames needed to reach 2PI(360angle) but in this line use delta this means how many seconds needed to reach 2*PI /
export var cycle = 1.0
// In each frame accu will be incremented(+=) we want to reach 2
pi
var accum = 0.0

func _physics_process(delta):
/In this case the accum var after one sec will be equal pi2 which is 360angle but in radians /
accum += delta * (1.0 / cycle) * PI * 2.0
/
accum/ pi2 but fmod is gives only remainder like modulo operator this line set to accum 0 if accum is equal pi2 and accum will never be bigger than 2PI/
accum = fmod(accum, PI * 2.0)
// Get a sinus you need to see images sin and cos, hard to explain
var d = sin(accum)
// Make a transform type variable
var xf = Transform2D()
Apply the motion vector
xf[2]= motion * d
// Set a node transform var
$body.transform = xf

LordViperion | 2019-02-02 15:12

Ok, it all made sense. So basically it’s just accumulation so as to “draw a graph”. I tried other trigo functions as well, cos and tan, giving me different effects, which look cool.

ryugomez | 2019-02-03 00:00

Yes draw a graph and adds a motion vector, for combined movement effect.

LordViperion | 2019-02-03 13:38