ros2-for-unity icon indicating copy to clipboard operation
ros2-for-unity copied to clipboard

Can you provide a listener example for joint_states?

Open terkaa opened this issue 1 year ago • 1 comments

Hi,

Could you please provide an example on how to listen the topic /joint_states and print individual joint positions in Unity Debugger.log?

Tero

terkaa avatar Aug 24 '24 07:08 terkaa

`using System; using UnityEngine; using sensor_msgs.msg;

namespace ROS2 {

public class JointStateListener : MonoBehaviour {

private ROS2UnityComponent ros2Unity;
private ROS2Node ros2Node;
private ISubscription<JointState> jointStateSub;

void Start()
{
    // Find the ROS2UnityComponent in the scene
    ros2Unity = GetComponent<ROS2UnityComponent>();
}

void Update()
{
     if (ros2Node == null && ros2Unity.Ok())
    {
        // Create a node
        ros2Node = ros2Unity.CreateNode("joint_state_listener_node");

        // Subscribe to the /joint_states topic
        jointStateSub = ros2Node.CreateSubscription<JointState>(
            "/joint_states",
            msg =>
            {
                for (int i = 0; i < msg.Position.Length; i++)
                {
                    Debug.Log($"Joint {i}: Position {msg.Position[i]}");
                }
            });
    }
}

} }`

terkaa avatar Aug 25 '24 15:08 terkaa