How can I correctly position an object to PinJoint2D dynamically by code ?

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

Hi, I want to create a code to make a simple mechanism :

  1. fixed point
  2. bar rotating about that fixed point but, rotates about one of its end points (not about the center of bar).

My program will ask a bar properties (length, position etc) first. Then according to bar properties, dynamically assing one of its end point (I defined start and end Position2D objects) to pin joint which connects fixed ground and bar.

My tree of nodes like that :

Node2D
+A_StaticPoint (as StaticBody2D - @ 96,144 global coordinate)
++CollisionShape2D
+Link1 ( as RigidBody2D @ 160,144 global coordinate)
++CollisionShape2D
++start (@ 160,144 global coordinate)
++end (@ 160,194 global coordinate)
+Link1_A_Pin (as PinJoint2D)

My GDscript in root node (Node2D) is :

extends Node2D

onready var fixed_point_A = get_node(“A_StaticPoint”)
onready var link1 = get_node(“Link1”)
onready var pin_A_link1 = get_node(“Link1_A_Pin”)
onready var link1_start_point = get_node(“Link1/start”) # Position2D child node of link1

func _ready():
var fixed_to_start_point = (link1_start_point.get_global_position() - fixed_point_A.get_global_position()).round()

link1.position =(link1.get_global_position() - fixed_to_start_point).round()
pin_A_link1.set_position(fixed_point_A.get_position().round())
pin_A_link1.set_node_a(fixed_point_A.get_path())
pin_A_link1.set_node_b(link1.get_path())

func _draw():

draw_circle(link1_start_point.get_global_position(),5.0,Color(1,0,0,1))
draw_circle(link1.position,5,Color(0,1,0,1))
var label = Label.new()
var font = label.get_font("")
draw_string(font,Vector2(30,30),str(link1.get_rotation_degrees()),Color(1,1,0,1))
draw_string(font,Vector2(30,44),str(link1_start_point.get_global_position() ),Color(1,1,0,1))
pass

Code does :

  1. in ready() ::
    1.1. determines the initial ( fixed point and bar are breaked apart from each other, not touching) positions >> finds the Vector2() object which defines : start point(which will be pinned) of link1(bar) Vector2() to fixed point’s origin point
    1.2. shift link1’s position to fixed point’s position
  2. in _draw() ::
    2.1 I want to see where is the points of link1’s origin and start point’s locations and put them into string to check.

Result is error!

  1. I tried to change position of link1(bar) and I saw that pinjoint2D is a weak joint such that, I can move link independently! How does it pin two bodies each other while I can move each bodies seperately after pinned them?

I could not move rigidbody2D to another position and connect it to a fixed ground object by using pinjoint2D object. What is wrong about my code? Thanks.