How to measure, and store, the angle of a raycast hitting a collider

Hi there,

I’m still very new to Unity so I apologise for posting what might be a very simple question.

What I would like to do is the following: I’ve got a very simple Raycast gun script I’ve written (which works just as it should), but I’m having trouble measuring the angle at which Camera.main is facing the collider when the Ray hits. The reason I’d like this angle, is that at the point where the Raycast hits the collider I’m instantiating a bullet prefab and I’d like it to bounce toward the player from the wall.

Here’s the script I have at the moment:

public class Player_Shoots : MonoBehaviour {

	public float clipSize = 6;
	public GameObject debrisPrefab;

	float cameraDirection;

	// Use this for initialization
	void Start () {
	}

	// Update is called once per frame
	void Update () {

		if (Input.GetMouseButtonDown (0) && clipSize > 0) {
			// Reduce ammo in clip by 1 per click
			clipSize--;
			// Raycast 
			Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
			RaycastHit hitInfo;

			if(Physics.Raycast(ray, out hitInfo)){
				Vector3 hitPoint = hitInfo.point;

				// Instantiate our bullet at the hitPoint
				if(debrisPrefab != null){
					GameObject bullet = (GameObject)Instantiate(debrisPrefab, hitPoint, Camera.main.transform.rotation);
					// When our bullet is instantiated at the hitPoint, give it upward and inverse camera direction velocity
					Debug.Log (Camera.main.transform.rotation);
					bullet.rigidbody.AddForce(0, 400 , 0);
					// What I would like here would be to get the Camera.main.transform.rotation and save it to a varialbe, and then pass a negative version into Addforce(DIRECTION, 400, 0)
				}
			}
		}
	}
}

Any help would be much appreciated!

33621-ray-simple.png

Ok I’m not 100% sure about this but I think you’re misunderstanding what rigidbody.AddForce does. I’m assuming this based on your comment “… version into Addforce(DIRECTION, 400, 0)”. The first variable is just the force in on the x axis.
You have two versions of AddForce: one that uses a Vector3 force and one that uses 3 floats for x,y and z. Both version do the same thing apply a force on each axis.

Now if I understand your question correctly then the answer is pretty simple. You just need two things: The direction of the camera and the strength of the force you want to apply in that direction. The first is just Camera.main.transform.forward. That’s the direction vector. So just take it, negate it and multiply it by your strength(I chose 20 here).

bullet.rigidbody.AddForce(-Camera.main.transform.forward * 20);

I hope I understood you right and this is what you wanted :smiley: