- Home /
raycast hit add force problem, help needed please
I have this current script (see below), what i'm trying to do is have a wall (made up of seperate blocks) and when you touch a block it adds force and falls down with gravity.
In my scene I just have "castle_brick" prefabs which at the moment are just cubes with rigidbody attached, duplicated to form a wall.
What is happening at the moment is when I touch any brick it plays the sound multiple times and all the bricks fly away together (as though one touch on any brick is hitting them all at once)
any help in what i'm doing wrong would be appriciated, cheers :)
private var ray : Ray;
private var rayCastHit : RaycastHit;
var mySound: AudioClip;
var bloodPrefab : GameObject;
var direction = transform.forward;
var force = 2000;
function Update(){
if(Input.GetMouseButtonDown(0)){
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, rayCastHit)){
//add name of object/button to affect in ""
if(rayCastHit.transform.name == "castle_brick"){
//play sound
audio.clip = mySound;
audio.PlayOneShot(mySound);
Debug.Log("Score!");
Scorecounter.Counter +=5;
//create blood prefab
var rot = Quaternion.FromToRotation(Vector3.up, rayCastHit.normal);
Instantiate(bloodPrefab, rayCastHit.point, rot);
//add force to object
rigidbody.AddForceAtPosition(force * direction, rayCastHit.point);
Debug.Log ("hit castle_brick!");
}
}
}
}
Answer by robertbu · May 17, 2013 at 02:20 PM
What object do you have this script attached to? Line 31 implies that you have this attached to the bricks themselves. Is that true or do you have it attached to another rigidbody?
It "should" be attached to another game object (not the bricks). You don't want a raycast for every brick. Then on like 31 you would apply the force to whatever was hit:
hit.rigidbody.AddForceAtPosition(force * direction, rayCastHit.point);
As for 'direction' you may want to experiment with using the negated normal of the hit.
Note you are getting multiple hits because your Raycast() returns true for any brick, not just the brick this script is attached to. So every brick is thinking it is hit, and every brick is playing the audio, and every brick is adding force.
I have the script attached to an empty gameobject called "script_manager".
when I add the line hit.rigidbody.AddForceAtPosition(force * direction, rayCastHit.point);
I get "unknown identifier: 'hit'. I changed it to rayCastHit.rigidbody.AddForceAtPosition(force * direction, rayCastHit.point);
this hit and added the force to individual bricks but it still played the sound for all of them.
Do I need to name every brick with a different name?
I got it working now, I had the script attached to some of the bricks also hehe thankyou very much for helping me out! :)
Sorry about the 'hit'. As you figure out it should have been rayCastHit.
no problem :) thanks for helping me get it working!