- Home /
rigidbody.AddForce affects all clones
Hello, on scene I have 3 balls with Ball.cs script attached to each of them. And when I push ball with mouse all balls start moving, but I need that only one that I touch moves.
Here is my FixedUpdate:
void FixedUpdate() {
if(!isMoving) {
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100)) {
if(hit.collider.tag == "Ball") {
startPos = hit.point;
}
}
}
if (startPos != Vector3.zero && Input.GetMouseButtonUp(0)) {
endPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = endPos - startPos;
direction.Normalize();
float distance = Vector3.Distance(endPos, startPos);
rigidbody.AddForce(direction * distance * force * Time.deltaTime, ForceMode.Impulse);
isMoving = true;
}
} else {
if(rigidbody.velocity.sqrMagnitude == 0) {
isMoving = false;
startPos = endPos = Vector3.zero;
}
}
}
Answer by NoseKills · Jun 18, 2014 at 03:25 PM
You are not checking which ball gets hit. You just have a check in all the balls that if a click is made and a object with the Ball tag is hit, the object running the script gets affected. All the balls run the script and IF a click hits a ball, all balls get affected.
On top of checking the hit.collider.tag matches, check also that the gameobject of the hit is the same as this.gameObject.
It would be better to move this entire logic out of the individual balls and into a game manager object, otherwise there's a lot of unnecessary raycasting going on
Hey @tanoshimi, can you send me to some good example of game manager
Your answer
![](https://koobas.hobune.stream/wayback/20220613151827im_/https://answers.unity.com/themes/thub/images/avi.jpg)