I written up a script that allowed any one of my game objects to rotate in a circular motion however it always seems to reset the object to the center of the screen when I play the game and never to the position I started it from. I got no clue about how to go around this but I’ve been trying to look into it. If anyone can help me out thanks in advance.
using UnityEngine;
using System.Collections;
// Circular Motion Script
public class CircularMotionScript : MonoBehaviour
{
public float mPosition = 0F;
public float mRadius = 2.5F;
void Update ()
{
// Move game object in a circular motion
mPosition += .02F;
transform.position = new Vector3(Mathf.Sin(mPosition)*mRadius, Mathf.Cos(mPosition)*mRadius, 0);
}
}
Well, what you describe is exactly what you do there. Sin() and Cos() returns a value between -1 and 1. You multiply this value by your radius so the value is in between -radius and radius. Then you use it as absolute position. This way you will always rotate around 0,0,0
What you need is an offset. This can be saved at start like this:
using UnityEngine;
using System.Collections;
public class CircularMotionScript : MonoBehaviour
{
public float mPosition = 0F;
public float mRadius = 2.5F;
private Vector3 m_InitialPosition;
void Start()
{
m_InitialPosition = transform.position;
}
void Update ()
{
mPosition += Time.deltaTime * 1.0f; // 1.0f is the rotation speed in radians per sec.
Vector3 pos = new Vector3(Mathf.Sin(mPosition), Mathf.Cos(mPosition), 0);
transform.position = m_InitialPosition + pos * mRadius;
}
}
You don’t need to do all of that… just make the object you want to move circularly a child of a stick (cube game object) , put your object at the tip of the stick… then attach a script to the stick to make it rotate
function Update(){
transform.Rotate(0,0,Time.deltaTime);
}
make sure not to render the stick in camera…
the stick length is the radius of the circle…