Search Unity

How do I fix movement of a game object to a set distance from a point (a circle)?

Discussion in 'Scripting' started by ecnalyr, Mar 17, 2011.

  1. ecnalyr

    ecnalyr

    Joined:
    May 23, 2010
    Posts:
    38
    I am trying to make a ship move around a central point at a fixed distance away from that point (along a circle around that point).

    What is an efficient way to achieve this?

    The actual movement will be dictated by screen touches - the ship will move to the closest point along that circular path (via that circular path) that is closest to the screen touch.
     
  2. majmun

    majmun

    Joined:
    Feb 2, 2011
    Posts:
    140
    how to make a ship that is moving in circle?

    my idea would be (in C#):

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class Ship: MonoBehaviour
    6. {
    7. public float Speed;     //set this to something like 10
    8. public float Rotation;  //set this to something like 1
    9.  
    10.     void Update ()
    11.     {
    12.         transform.Translate(Vector3.forward * Speed * Time.deltaTime);
    13.             transform.Rotate (0, Rotation, 0);
    14.     }
    15. }
    16.  
    Maybe the code needs some improvements but the idea is there.

    So simply each frame boat goes forward for some amount and also each frame boat rotates for some amount,

    if SPEED and ROTATION are always constants, the boat will make circles for sure
    Speed and rotation are factors for radius of the circle, so you will have to change them to get the size that you like.

    Experiment with speed and radius.

    I think that speed represents how big circle would be
    and radius represents how fast would boat make loops.
     
  3. Jesse Anders

    Jesse Anders

    Joined:
    Apr 5, 2008
    Posts:
    2,857
    To find the closest point on the circle perimeter to a point (untested pseudocode):

    Code (csharp):
    1. vector2 diff = query_point - circle_center;
    2. diff.normalize();
    3. vector2 closest = circle_center + diff * circle_radius;
    Note that this may fail if the query point is very close to the circle center.

    Once you have the closest point, you can determine in which direction around the circle the distance to the closest point is the least using some simple vector math, and then move the ship in that direction. (I obviously skipped over some details here, but you can post back if you have specific questions.)
     
unityunity