- Home /
checking collision with polygon collider using ray cast and instantiating objects issue
I'm trying to check collision with Polygon collider using Raycast on my field in my Unity game. And then create crop on position of ray cast if conditions met by clicking button. Even though it checks collision perfectly i have a few issues that i just cant figure out how to fix. Like:
my shooter game object teleport on scene randomly, but raycasting is always correct O_o. Instantiated crop disappear in moment of next instantiation... Can some one help me to fix it? Here is the code: public class PlayerRay : MonoBehaviour { float borderLeft = -4.34f; float borderRight = 3.85f; float borderUp = 1.61f; float borderDown = -2.32f;
public GameObject field;
public GameObject shooter;
public Transform shooterPos;
PolygonCollider2D fieldCollider;
public GameObject repka;
private void Start()
{
fieldCollider = field.GetComponent<PolygonCollider2D>();
}
void Update()
{
}
public void Sow()
{
Vector3 rayCastPos = new Vector3(Random.Range(borderLeft, borderRight), Random.Range(borderDown, borderUp), 0);
shooter.transform.Translate(rayCastPos);
Debug.DrawRay(transform.position, transform.forward * 10, Color.yellow);
RaycastHit2D hit = Physics2D.Raycast(rayCastPos, Vector3.forward);
if (hit == fieldCollider)
{
Debug.Log("We hit collider");
Instantiate(repka, shooterPos);
}
else
{
Debug.Log("There is no colider at: " + rayCastPos);
}
}
}
Answer by Oleksii_Stetsenko · Dec 04, 2021 at 06:02 PM
I found solution! It's just that i tried to use Transform overload for instantiate instead of using Vector3
. Because i forgot to add "rotation" as third parameter. So i switched to Vector3
overload, added Quaternion.identity
for rotation and it's all works just fine now :) Here is the fix:
Instantiate(repka, rayCastPos, Quaternion.identity);
Your answer
Follow this Question
Related Questions
Raycast bullet impact and instantiating particles 3 Answers
problem with instatiated clone 2 Answers
How To: Spawn object on raycast collision. 2 Answers
help with scripting combo points 1 Answer