- Home /
C# SphereCast isn't Inaccurate
Hi everyone, I have been a using a SphereCast instead of a Raycast to try and make it more inaccurate. However my SphereCast doesn't seem that inaccurate and still misses the object I want to hit. Any idea what is wrong with my script?
public float Distance = 100;
public RaycastHit hit;
if(Physics.SphereCast(gameObject.transform.position, 0.5f, transform.forward, out hit, Distance))
Have you tried printing out what it is hitting?
Debug.Log("Hit: " + hit.transform.name);
Generally, when using sphere casts, if the object that you are trying to hit is behind an object that the sphere cast runs into on it's path then it will hit the object that's in between the caster and the target and stop right there, returning the 'wrong' object (or, at least, not the one that you are expecting to detect in your case).
Does the target that you're trying to hit have a collider or a rigidbody? Are you also sure that it's within the 100m distance, and that your transform's forward direction is what you expect it to be? You can also try setting up your target object directly in front of your caster, and use Vector3.forward ins$$anonymous$$d of transform.forward for debugging purposes.
Essentially, Sphere-casting just works, so if you're not getting the desired results then there is something incorrect with the way that it's being implemented. :)
The only problem might be the physics not being updated when you call the sphere cast if the object is moving fast.
You should try doing a Debug.DrawRay to ensure that you are pointing where you think you are.
Just as long as you understand the difference between Vector3.forward and transform.forward.
Vector3.forward is in world space, meaning that it always points along the world's z axis, while transform.forward is in local space, meaning that it points along the transform's z axis.
Is your transform rotated 90 degrees along the x axis? This would cause transform.forward to point down.
Answer by Ochreous · Apr 30, 2013 at 09:09 PM
I figured it out. I switched transform.position to gameobject.transform.position since I'm using this with Unity's default FPS character controller I want it to be relevant to that gameobject.
That effectively does nothing, because gameObject.transform and transform are the same thing. ;)
Your answer
Follow this Question
Related Questions
Saving final score and displaying on main menu 1 Answer
null texture passed to GUI.DrawTexture 0 Answers
How to Name Individual Buttons Within a List 2 Answers
c# Adjust In-Game audio 1 Answer
C# How to Detect Edges of a Collider 0 Answers