with-RL
로봇 / ROS2024년 2월 13일

URDF를 이용해 만든 로봇에 Unity 자동차 연결하기 (4)

이번 포스팅은 URDF를 이용해 만든 로봇에 Unity 자동차 연결하기 (3) 과정을 통해서 만들어진 Unity 로봇에 카메라를 부착하고 ROS와 연동해 보는 과정입니다.

이 포스트는 다음 과정을 완료한 후에 참고하시길 바랍니다.

1. Unity 로봇에 카메라 부착하기

using System;
using System.Text;
using UnityEngine;
using Unity.Robotics.ROSTCPConnector;
using Unity.Robotics.ROSTCPConnector.MessageGeneration;
using RosMessageTypes.Sensor;
using RosMessageTypes.Std;

public class ImageRawPublisher : MonoBehaviour
{
    [SerializeField] private RenderTexture renderTexture = null;
    [SerializeField] private string topicName = "img_raw";
    [SerializeField] private float publishFrequency = 0.1f;

    ROSConnection ros;
    private float timeElapsed = 0.0f;


    private void Start()
    {
        ros = ROSConnection.GetOrCreateInstance();
        ros.RegisterPublisher<ImageMsg>(topicName);
    }

    private void FixedUpdate()
    {
        timeElapsed += Time.deltaTime;

        if (timeElapsed >= publishFrequency)
        {
            Texture2D texture = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGBA32, false);
            RenderTexture.active = renderTexture;
            texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0, false);

            ImageMsg img_raw = texture.ToImageMsg(new HeaderMsg());
            ros.Publish(topicName, img_raw);


            timeElapsed = 0;
        }
    }
}

2. ROS와 Unity 연동하기

$ cd ~/Workspace/ros_ws
$ source install/setup.bash
$ ros2 launch car_tutorial unity.launch.py

$ ros2 run teleop_twist_keyboard teleop_twist_keyboard