- Home /
RaycardHit2D not working on Sprites?
I've taken out some of the code so its easier to read but being as there is 2 tags one for unpassable terran and one for tall grass, ive put the tall grass as more of a 3d raycast so they dont interfere with eachother but the tall grass only checks once and stops :\
using UnityEngine;
using System.Collections;
public class PlayerStats : MonoBehaviour {
Vector2 startPoint;
Vector2 endPoint;
public float speed;
private float increment = 0;
bool isMoving;
public static int walkCounter;
int walkCounter2;
bool isInCombat;
bool ableMove;
RaycastHit2D hit;
Animator anim;
public GameObject CameraMain;
public GameObject CameraCombat;
public GameObject[] teleportLoc;
void Start() {
startPoint = transform.position;
endPoint = transform.position;
anim = GetComponent<Animator>();
walkCounter2 = Random.Range(5,15);
}
void Update () {
Animations();
if(increment <= 1 && isMoving){
increment += speed/100;
}
else
isMoving = false;
if(isMoving)
transform.position = Vector2.Lerp(startPoint, endPoint, increment);
if (!isInCombat)
{
else if(Input.GetKey("a") && !isMoving)
{
if (Physics2D.Raycast (transform.position, -Vector2.right, 1))
{
hit = Physics2D.Raycast (transform.position, -Vector2.right, 1);
if(hit.collider.tag == "Collision") {
ableMove = false;
}
}
if(ableMove)
{
calculateWalk();
increment = 0;
isMoving = true;
startPoint = transform.position;
endPoint = new Vector2(transform.position.x - 1, transform.position.y);
}
ableMove = true;
}
}
}
void calculateWalk () {
if(Physics.Raycast(transform.position, Vector3.forward, 1))
{
walkCounter++;
Debug.Log(walkCounter);
}
if(walkCounter >= walkCounter2) {
walkCounter2 = Random.Range(5,15);
walkCounter = 0;
enterCombat();
}
}
Answer by jann1 · Apr 09, 2014 at 03:27 PM
Maybe your collider is set to trigger? Or the GameObject youre trying to hit isnt tagged correctly. Do you use a rigidbody2D instead of a rigidbody?
I worked out it wasn't working probably because there was 2 different tagged sprites and they were interfering with each other. Do you know how i can fix that?
Sorry I dont really understand what the problem is. $$anonymous$$aybe you can provide more context? Or you already have solved it yourself?
2 objects with 2 different tags where both hitting the raycast when i wanted to pick which ones hit it. I just put them on layers and fixed it, thanks anyways.
Your answer
![](https://koobas.hobune.stream/wayback/20220613142325im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Cutting a Sprite 0 Answers
Raycasting in 2D is not working 0 Answers
OnCollisionEnter2D is not working 0 Answers
0 Understanding of raycast2D commands 2 Answers
New UI ~ Check for mouse-hover 1 Answer