- Home /
circular movement with force not working
I have a stardart sphere game object which is prefab with rigidbody and target script. in target script Im giving circular movement to this sprere object.
And I have spawn script which accepts 3 point and 3 object which Instantiates theese 3 object in 3 point.
My circular movement is working, but when i try to add force through the camera it doesnt work.
How Can I achive both circular movement and add force through the camera?
My target and spawn scripts are below.
target
public class Target : MonoBehaviour { public float health = 50f;
public float speed;
public float width;
public float height;
float timeCounter = 0f;
Vector3 startPoint;
int direction;
void Start()
{
int number = Random.Range(1, 255);
direction = number % 2 == 0 ? 1 : -1;
startPoint = new Vector3(transform.position.x, transform.position.y, transform.position.z);
}
// Update is called once per frame
void Update()
{
timeCounter += Time.deltaTime * speed;
float x = direction * Mathf.Cos(timeCounter) * width + startPoint.x;
float y = Mathf.Sin(timeCounter) * height + startPoint.y;
float z = startPoint.z;
transform.position = new Vector3(x, y, z);
}
}
spawn public class SpawnScript : MonoBehaviour { public Transform[] spawnPoints; public GameObject[] balloons;
void Start()
{
StartSpawn();
}
void StartSpawn()
{
for (int i = 0; i < spawnPoints.Length; i++)
{
GameObject target = Instantiate(balloons[i], spawnPoints[i].position, Quaternion.identity);
Rigidbody rbTarget = target.GetComponent<Rigidbody>();
rbTarget.AddForce(Camera.main.transform.position * 2f);
}
}
}
Answer by OlleStarclassic · Oct 09, 2021 at 09:12 PM
I guess you should not move your targets every frame by updating its transform.position.
The AddForce to the rigidbody can’t update the targets position because your moving its position yourself every frame.
Maybe you can add movement to the target via its AddForce method only and not updating its position every frame?
As a side note:
rbTarget.AddForce(Camera.main.transform.position * 2f);
This won't be very effective at moving toward the camera. It should probably be something more like:
// It'll be much more efficient to cache the main camera somewhere
rbTarget.AddForce((target.transform.position - mainCam.transform.position).normalized * 2f);
yess you're right. I'm updating my z position with my start position. so even though i've added force it updated itself as start position. so I've change my circular movement code like below and problem solved. silly me :)
from float z = startPoint.z;
to float z = gameObject.transform.position.z;
thank you for your help!!
Your answer
