Hey guys, I was trying to find an answer to this on Unity Answers already but haven’t gotten any useful feedback yet. I was working on a RayCast script for my Multiplayer Game that adds force to objects, pretty basic. This script has worked in other projects or levels, but now it doesn’t seem to work anymore. Basically: No matter what I set as Vector3 in the variable “DirectionRay”, the object always gets force added from the Left. I would be thankful if someone could take a look and help me! Thank you in advance.
//Range of the Ray we are sending out
public float Range = 1000.0f;
//How much force is added to rigid bodys
public float Force = 1000.0f;
void RayShoot ()
{
//Tells us if a the Ray has hit something
RaycastHit Hit;
//Direction of the Ray that the player has sent out
Vector3 DirectionRay = transform.TransformDirection (Vector3.forward);
//Sets the Fire Rate
if(FireTime <= Time.time)
{
//If fire Rate is surpassed, fire the Ray
FireTime = FireRate + Time.time;
Debug.DrawRay(FirePoint.position, FirePoint.forward , Color.red);
//If the Ray is sent out...
if(Physics.Raycast(FirePoint.position, FirePoint.forward ,out Hit, Range))
{
Quaternion hitRotation = Quaternion.FromToRotation(Vector3.up, Hit.normal);
if(Hit.collider)
{
//Check if it hit and Object
Debug.Log(Hit.collider.name);
}
if(Hit.rigidbody != null)
{
//Make the object fly away by adding force to it
Hit.rigidbody.AddForceAtPosition(Force * DirectionRay, Hit.point);
//Check if it hit and Object
Debug.Log("Added Force to Rigid Body");
}
}
}
}
Note: This is a more simplified copy of the Original script, only including the parts that I thought were necessary to solve this.
Yes, FirePoint.forward is the Camera, so the point from which the RayCast is sent from. DirectionRay gets the transform that is hit and determines where it’s forward is, giving the raycast a direction to send the ball flying to. I could also just write in transform.forward I think, but I’m not sure. This is how it has worked for me so far
It’s probably worth noting that AddForceAtPosition may induce torque. If that’s not a desired result, use AddForce instead. Oh and since I cannot see beyond your snippet, make sure physics are called under FixedUpdate.
Thank you, this helped a bit, as the ball no longer goes left. What do you mean with FixedUpdate (sorry, I still haven’t gotten around all the terminology after all this time haha ).Because really, “transform.forward” (or DirectionRay in that matter) should work normally.
If that’s your intention, go for it. Just that I notice the vector you’re using to raycast is not the same vector applied to the rigidbody, nor the rigidbody’s forward direction.