How can you prevent a RigidBody2d from moving on x axis?

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

I’m making a 2d platformer and I wanted to add a physics based button, but I got stuck when I couldn’t make the moving part go only up and down.

Can you show us your script?

MikeSundaysGameDev | 2021-04-10 09:52

I don’t really have a script yet. I wanted to start with this moving part, because my plan was to check the local coordinates of it and based on that information make it activate other things like doors.

Foggy | 2021-04-10 11:25

Well but you probably have a moving script already where you faced that problem right?

MikeSundaysGameDev | 2021-04-10 11:55

I don’t. I wanted to use the rigidbody2ds physics to move it up and down. I set the gravity_scale to negative and made an invisible stopper above it. I then realised that I need it to not move sideways.

Foggy | 2021-04-10 21:28

Okay, I made it, but it surely is not perfect. From the players perspective it could be weird that a button bounces them back a bit (or bounces other rigidbody2d) + in an edge case if you collide with it at enough high velocity it will go flying to the side. Also I would really like to not unnecessarily overwork the engine.

extends RigidBody2D
onready var start = position

func _integrate_forces(state):
	if position != start:
		state.set_linear_velocity(Vector2((start.x - position.x) * 400, state.get_linear_velocity().y))

Foggy | 2021-04-10 23:02

You can fix that issue by creating a different layer for the physics based button that isn’t masked by the other rigidbodies(the button cant mask them either)

MikeSundaysGameDev | 2021-04-12 21:51

:bust_in_silhouette: Reply From: Chubbybond

If there aren’t any movement already, i’d call (my movement variable here).x = 0 not sure if this helps or not.

Unfortunately it just slows it down for some reason. I think one frame it moves and the other it stops and that cycle repeats. Thank you for help anyways

Foggy | 2021-04-05 15:56