在场景中,我有 3 个球,每个球都附有 Ball.cs 脚本。当我用鼠标推球时,所有的球都开始移动,但我只需要我触摸的那个移动。
这是我的固定更新:
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;
}
}
}