- Home /
How to orbit UI object depending on another gameobject position (2D)
Hello, I have a gameobject that has a child (canvas) set in world space & in that canvas is a child image. I'm trying to get the image to rotate/orbit around the gameobject depending on player position. so basically if the player is on the left side of the gameobject the image should be on the right side of the gameobject & if the player moves to the right side of the gameobject the image should orbit around the gameobject to the left side. I searched online & couldn't find a solution any help??
Answer by icehex · May 15, 2020 at 07:05 AM
Tested this & works properly in 3D. May require a couple of adjustments for 2D. Attach this script to the gameObject at the center of the GUI and Player. If you want them not to be exactly opposite, that can be done by adjusting the normalized vector by giving it a rotation using a Quaternion (i.e. multiply by a new Quaternion.Euler(0, 90, 0), I think). Let me know how it goes!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GUIMover : MonoBehaviour
{
public Transform playerObject; //this is your player's object
public Transform guiObject; // this is your GUI's object
public float guiRadius = 2f; // how far do you want the GUI to be from the central gameObject?
void Update()
{
// if you want the player and GUI to be equal distances from the center at all times, remove guiRadius and ".normalized"
guiObject.transform.position = this.transform.position + guiRadius*(this.transform.position - playerObject.position).normalized;
// use this if you want the object to always point towards; you may have to rotate the axes for 2D
guiObject.LookAt(this.transform);
}
}
Hello, thank you for this. The script made some improvements it is orbiting but it does needs some adjustments. im going to try to see what I can do & if I can't come up with a solution im going to return with questions. thank you.
@Cookiemonster04 sounds good. Please accept the answer if it solves your initial question. You can post new ones as needed
Your answer
![](https://koobas.hobune.stream/wayback/20220612234329im_/https://answers.unity.com/themes/thub/images/avi.jpg)