Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

2D How to make an object orbit around the player according to the position of a target.

Discussion in 'Scripting' started by popoleybaba, Jul 16, 2020.

  1. popoleybaba

    popoleybaba

    Joined:
    Aug 21, 2017
    Posts:
    3
    Hello!

    I am trying to make some kind of threat indicator. It will point towards an enemy and track the enemy in an orbital fashion. The image below will definitely explain it better. The black circle is the player and the red triangle is the indicator. The red triangle can only move on the green circle and always points towards the red circle. I have succesfully done the pointing towards the red circle part but how do I move the pointer in the orbit accordingly? How would you go about coding this? questionUnity.png
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    If you have the arrow origin/pivot point in the center of the players transform then you simply calc the vector towards the enemy and then rotate the arrow to that angle.

    Code (CSharp):
    1. public Transform Player, Arrow, Enemy;
    2.  
    3. private void Update()
    4. {
    5.     //Calc Vector from player to enemy
    6.     var direction = Enemy.position - Player.position;
    7.     //Calc rotation from the player to enemy.
    8.     var rot = Quaternion.LookRotation( Vector3.forward, direction);
    9.     //Apply rotation
    10.     Arrow.rotation = rot;
    11. }
     
  3. popoleybaba

    popoleybaba

    Joined:
    Aug 21, 2017
    Posts:
    3
    Thanks alot!