Reputation: 21
I am following a course for Godot 3 but I am using Godot 4. In the course a 2D object is instantiated and placed at a random point in the scene using
Object.transform = Transform2D(Vector2(X,Y)
So it returns "parser error: no constructor of "Transform2D" matches the signature "Transform2D(Vector2D)" How can I fix it?
I already tried with position and global_position but didn't work.
Upvotes: 2
Views: 5253
Reputation: 40295
First of all, if you only want to change the position of a transform, you can set its origin
.
And yes, you could write to position
or global_position
.
However, none of that would work with a rigid body.
The reason why is because the physics server is in charge of moving the rigid body, so when you set its position you are fighting it (you move it, and the physics server moves it back).
You could take charge of the motion of the rigid body by "freezing" to kinematic mode, but there is an easier and better solution if you only want to set the position...
I have answered variations of this question before.
I could vote to close this as a duplicate, but instead I'll take the opportunity to consolidate the answers here.
The following code tells the physics server to move the rigid body where you want it.
Godot 3, RigidBody2D
:
Physics2DServer.body_set_state(
get_rid(),
Physics2DServer.BODY_STATE_TRANSFORM,
Transform2D.IDENTITY.translated(Vector2(1.0, 2.0))
)
Godot 3, RigidBody
:
PhysicsServer.body_set_state(
get_rid(),
PhysicsServer.BODY_STATE_TRANSFORM,
Transform.IDENTITY.translated(Vector3(1.0, 2.0, 3.0))
)
Godot 4, RigidBody2D
:
PhysicsServer2D.body_set_state(
get_rid(),
PhysicsServer2D.BODY_STATE_TRANSFORM,
Transform2D.IDENTITY.translated(Vector2(1.0, 2.0))
)
And the elusive correct way to teleport a RigidBody3D
in Godot 4:
PhysicsServer3D.body_set_state(
get_rid(),
PhysicsServer3D.BODY_STATE_TRANSFORM,
Transform3D.IDENTITY.translated(Vector3(1.0, 2.0, 3.0))
)
Of course, you would pass the vector with the position you want.
These codes are meant to run on an script attached to the rigid body. If you need to run them somewhere else, you need to get the result of get_rid()
from a reference to the rigid body you want. And, of course, you can change the vector to the position want.
They also serves as an example of creating a translation transform (although it is not the only way to do it).
A transform, as you would know, can represent more than just a translation (they can represent rotation, scaling, skewing and mirroring too) so the transform does not have a constructor that simply takes a vector. Hence the error in question.
Upvotes: 8