- Home /
Raycasting in a 2D side scrolling shooter
Ive been attempting to make a 2D side scrolling shooter. Howeverm=, i cant seem to get any kind of raycasting to work with 2D colliders. Ive been told to try linecast but i do believe that they cannot return information about the hit. Does anyone have any suggestions as to how i can go about achieving a raycast shooting mechanic to work with 2D colliders?
Answer by maxkunes · Jan 03, 2014 at 07:22 PM
Your in luck, I've been working with 2d raycast for awhile and just to start make sure your using Racast2d not the normal one because that will not collide with ANY 2d collider and also make sure anything you are colliding with has a 2d collider of some sort.
Important If you are using a player with a collider or something make sure you are layering it to ignore raycast if the ray is hitting the player!!
Code for simple ray cast going downwards getting player height:
var HitObj : GameObject;
var Distance = 0f; //in case you didnt know f means float
function Update () {
var hit: RaycastHit2D = Physics2D.Raycast(transform.position, -Vector2.up);
// Making a new ray that will go straight down from the gameobject the code is attached to
Debug.DrawLine (transform.position, hit.point, Color.red);
//Debugging is optional but I like to see the red raycast line and it makes it easy to see what it's hitting
HitObj = hit.transform.gameObject;
// Again optional unless you want to access the hit with more detail
Distance = Mathf.Abs(hit.point.y - transform.position.y);
// grabbing the distance in a 2d plane AS A FLOAT
}
Not tested but it should work fine
Answer by Jishmael · Jan 03, 2014 at 10:16 PM
Okay, this is working much better (Thank you) however, the hit.point always seems to be outside of the collider, to solve this do i have to turn up the tick rate for the physics system?
Your answer
Follow this Question
Related Questions
Need urgent help to create projectile shooting script with raycasting 1 Answer
Should I use raycasting or colliders? 1 Answer
Using a MeshCollider for a tile-based 2d sidescroller terrain collisions 0 Answers
How do I make a raycast for a particle 1 Answer
Top Down Shooter Player Controller 1 Answer