简体   繁体   中英

rigidbody.AddForce affects all game objects with the same script component

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;
        }
    }
}

Like Nick Udell already mentioned, your comparison of the tag is the source of your problem. All three balls are executing the same script at nearly the same time. So if you click on of the balls, all three scripts will cast a ray at your mouse position and check if they hit a ball. Guess what? All of them hit a ball but not the ball they belong to.

You need to check if they are hitting the collider attached to their GameObject

if (hit.collider == collider) {
    // do stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM