Moving Platform Does Not Work As Intended

Godot Version

4.2

Question

I am trying to make a simple moving platform with the AnimatableBody2D and a script. I don’t want to use AnimationPlayer or anything like that. Just a script. Currently the platform is moving to the place I want and is coming back to where it is supposed to but the platform also is like on 2 different places at the same time.

using Godot;
using System;

public partial class SimpleMovingBlock : AnimatableBody2D
{
[Export]
private Vector2 speed = new Vector2(400, 0);
private Vector2 startingPosition;
private AnimatableBody2D movingPlatform;

private enum BlockState
{
	MOVING_RIGHT,
	MOVING_LEFT
}

BlockState currentState;

public override void _Ready()
{
	movingPlatform = this;
	startingPosition = this.Position;
	currentState = BlockState.MOVING_RIGHT;
}

public void MoveRight(double delta)
{
	movingPlatform.Position += speed * (float)delta;	
}

public void MoveLeft(double delta)
{
	movingPlatform.Position -= speed * (float)delta;
}

public override void _Process(double delta)
{
	GD.Print(movingPlatform.Position.X);
	GD.Print(currentState);
	if (currentState == BlockState.MOVING_RIGHT)
	{
		if (movingPlatform.Position.X >= startingPosition.X + 100)
		{
			currentState = BlockState.MOVING_LEFT;
		}
		MoveRight(delta);
	}
	else if (currentState == BlockState.MOVING_LEFT)
	{
		if (movingPlatform.Position.X <= startingPosition.X)
		{
			currentState = BlockState.MOVING_RIGHT;
		}
		MoveLeft(delta);
	}
}

}

image

I cant take a ss of what happens, because ss tools stop everything while i am taking it and then it wont show what exactly happens.

I am sorry that the post looks weird.

Well, your script says to move the platform to the right for at least 100px at 400px per second…

1 Like

I understand, please forgive my ignorant question.

I have changed my code to this and it works like a charm now.

using Godot;
using System;

public partial class SimpleMovingBlock : AnimatableBody2D
{
[Export]
private Vector2 speed = new Vector2(1, 0);
private Vector2 startingPosition;

private enum BlockState
{
	MOVING_RIGHT,
	MOVING_LEFT
}

BlockState currentState;

public override void _Ready()
{
	startingPosition = this.Position;
	currentState = BlockState.MOVING_RIGHT;
}

public void MoveRight()
{
	Position += speed;
}

public void MoveLeft()
{
	Position -= speed;
}

public override void _Process(double delta)
{
	GD.Print(Position.X);
	GD.Print(currentState);
	if (currentState == BlockState.MOVING_RIGHT)
	{
		if (Position.X >= startingPosition.X + 100)
		{
			currentState = BlockState.MOVING_LEFT;
		}
		MoveRight();
	}
	else if (currentState == BlockState.MOVING_LEFT)
	{
		if (Position.X <= startingPosition.X)
		{
			currentState = BlockState.MOVING_RIGHT;
		}
		MoveLeft();
	}
}

}