- Home /
Are Raycasts only used to check something? Why can't I use Raycasts to perform an action?
Hi! I've been playing around with Raycasts and SphereCasts and whatnot and currently i'm trying to perform an event for when a Ray has been activated, is this possible? Or are Rays only for checking or "see only" purposes?
Here is a picture of the Ray being activated when the ball is in sight, everything is working fine, the only issue is AddForce isn't actually affecting the Ball.

And here is the code for what i'm trying to do.
public void castRayCast()
{
float booster = 100;
objectPos = transform.position;
if (Physics.SphereCast(objectPos, rayRadius, Vector3.forward, out hitInfo, rayDistance))
{
rayAlive = true;
Debug.Log("Raycast has hit " + hitInfo.transform.gameObject.tag);
Debug.DrawRay(objectPos, Vector3.forward, Color.red);
GameObject ball = pongPrefab;
if (rayAlive)
{
ball.GetComponent<Rigidbody>().AddForce(transform.forward * booster, ForceMode.Impulse);
Debug.Log("Ray is Alive!");
}
else
Debug.LogError("Failed to bounce ball back");
}
else
rayAlive = false;
}
Any sort of help is appreciated! Thanks in advance :)
What is 'pongPrefab' in your code?
Is it a prefab from the project window as the name suggests? If so, thats why it isn't working, sinse you want to change the force of the instantiated ball (the one in the scene/hierarchy) ins$$anonymous$$d of the prefab which isn't the ball you are looking at in your scene...
ps. Is this all of the code? Because if so, the second if is pointless, as rayAlive will always be true...
Yeah pongBall is a prefab, it's never in the scene until it's been instantiated, hence why i created a "ball" gameObject to play around with it in code.
Nothing in the scene has Raycasting enabled apart from the ball, so Raycasting is always off unless it's hitting the ball.
Answer by Ibzy · Jun 25, 2015 at 03:55 PM
You are not checking anything from the RaycastHit, just if it hit.
if(hitInfo.transform.CompareTag("Ball")){
hitInfo.GetComponent<RigidBody>().AddForce(transform.forward * booster, ForceMode.Impulse);
}
This should check that your sphere hit the Ball, then get the RigidBody of it and apply the force.
I tried inputting your code but it still doesn't seem to be working. Although i'm just a little confused, isn't my first if statement checking if it hit something? And if so, AddForce to the ball?
Isn't that the same as checking (hitInfo.transform.CompareTag)? Just trying to understand the code, i'm not saying your wrong :)
ps. Everything in my scene has Raycasting disabled apart from the ball.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Cancel out a Addforce && Addtorque? 1 Answer
Question about topdown-movement and mouse-facing-foward-check 0 Answers
Further collision beyond the OnCollisionEnter() event 1 Answer