- Home /
Question by
TeozTroy · Sep 21, 2015 at 09:34 AM ·
2dinstantiateraycastraycasthit2d
Trying to get a 2D RayCast to instantiate a GameObject
Hi everyone, as the title suggests, I've been trying to create a 2d RayCast. I'm fairly new to C# and Unity as a whole, so I'm probably missing something fairly simple to see!
I want this raycast to detect shootable layers that I define. Firstly, the Debug.DrawRay doesn't show anything, secondly, the shoot method doesn't perform, nor does it show the Debug.Log message I placed within.
using UnityEngine;
using System.Collections;
public class ProjectileSystem : MonoBehaviour {
//SUMMARY
//These array lists can be added to as the game progresses.
//This array list allows for a neat and tidy code structure without dumping too many
//unneccesary lines of code for float declarations.
//
//
//Declaring an open array list for various ranged projectiles.
public int[] projectileDamage = new int[] { 15, 20 };
//Declaring an open array list for float timers between allowed shot projectiles
public float[] timeBetweenShots = new float[] { 0.5f, 0.6f, 2f };
//Declaring an open array list for range of various projectiles
public float[] rangeForShots = new float[] { 45f, 60f };
public GameObject arrow;
public float speed;
//Private declaration list
float timer;
Ray2D projectileRay;
RaycastHit2D projectileHit;
int shootableMask;
// Use this for initialization
void Awake () {
shootableMask = LayerMask.GetMask("Shootable");
}
// Update is called once per frame
void Update () {
timer += Time.deltaTime;
//We'll start with the basic arrow array first.
if (Input.GetButton("Fire1") && timer >= timeBetweenShots[0])
{
Shoot();
}
}
void Shoot()
{
timer = 0f;
//TODO
//Add in instantiation of arrow projectile sprite
projectileRay.origin = transform.position;
projectileRay.direction = transform.forward;
if(Physics2D.Raycast (projectileRay.origin, projectileRay.direction, rangeForShots[1], shootableMask))
{
Instantiate(arrow, transform.position, Quaternion.LookRotation(projectileRay.direction));
Debug.DrawRay(transform.position, projectileRay.direction, Color.green);
}
}
}
How would I go about getting the 2D raycasts to show, and also to instantiate an object based off of the start position and following through with the direction?
Many thanks in advance!
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612034439im_/https://answers.unity.com/themes/thub/images/avi.jpg)