Hi! I have a problem!

I want to add a circular motion to that sphere but everytime i press play the sphere goes in another direction. What i wrong?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LightMotion : MonoBehaviour
{
float timeCounter = 0f;

// Start is called before the first frame update
void Start()
{
    speed = 5f;
    width = 4f;
    height = 5f;      
}

// Update is called once per frame
void Update()
{
    timeCounter += Time.deltaTime*speed;

    float x = Mathf.Cos(timeCounter)*width;
    float y = Mathf.Sin(timeCounter)*height;
    float z = transform.position.z;

    gameObject.transform.position = new Vector3 (x, y, z);
}

}
ezgif.com-gif-maker

Do you mean the sphere moves away from where you placed it at design time?

This is because you are not taking the current (start) position into account. The sphere moves around the origin (0,0,0) of the world.

A simple solution would be to capture the start position, and then offset it when you move the sphere


private Vector3 startPosition;

void Start()
{
    speed = 5f;
    width = 4f;
    height = 5f;
    startPosition = transform.position;
}
void Update()
{
    timeCounter += Time.deltaTime*speed;

    float x = Mathf.Cos(timeCounter)*width;
    float y = Mathf.Sin(timeCounter)*height;

    gameObject.transform.position = startPosition + new Vector3 (x, y, 0f);
}

This is untested but should move the sphere around the position it was when the game started. Note that I have removed z because the startPosition already holds that value

1 Like

perfect! now everything’s work!
ezgif.com-gif-maker (1)

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms