0

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);
        }
    }
}

enter image description here

1 Answers1

0

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);
Jackdaw
  • 7,626
  • 5
  • 15
  • 33