Answer the question
In order to leave comments, you need to log in
Raycast not working in Unity 2D. What to do?
I have one control script sprite which is the player and another object tagged "enemy" which is the enemy. Here is the line of the control script that is responsible for the raycast:
void Punch()
{
RaycastHit2D hit = Physics2D.Raycast(gameObject.transform.position, transform.TransformDirection(Vector2.right), ray_length);
Debug.DrawRay(gameObject.transform.position, Vector2.right * ray_length, Color.red);
if(Input.GetKeyDown(KeyCode.E))
{
if (hit.collider != null)
{
if(hit.collider.gameObject.CompareTag("enemy"))
{
Debug.Log("enemy");
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class character_script_2 : MonoBehaviour
{
public string name;
public float velocity;
public float JumpForce;
public float timer;
public float punch_time;
public float ray_length;
public floor_on floortouch;
public GameObject punch;
private Rigidbody2D rb1;
public RaycastHit2D hit;
void Awake()
{
rb1 = gameObject.GetComponent<Rigidbody2D>();
}
void Update()
{
if(timer > 0)
{
timer -= Time.deltaTime;
}
//if(punch_time > 0)
//{
// punch_time -= Time.deltaTime;
//}
//else if(punch_time <= 0)
//{
//}
floor_on floortouch;
Move();
Jump();
Punch();
}
void Punch()
{
RaycastHit2D hit = Physics2D.Raycast(gameObject.transform.position, transform.TransformDirection(Vector2.right), ray_length);
Debug.DrawRay(gameObject.transform.position, Vector2.right * ray_length, Color.red);
if(Input.GetKeyDown(KeyCode.E))
{
if (hit.collider != null)
{
if(hit.collider.gameObject.CompareTag("enemy"))
{
Debug.Log("enemy");
}
}
}
}
// Движения персонажа
void Move()
{
if (Input.GetAxisRaw ("Horizontal") > 0)
{
transform.Translate (Vector2.right * velocity * Time.deltaTime);
transform.eulerAngles = new Vector2 (0, 0);
Debug.Log(Input.GetAxisRaw ("Horizontal"));
}
else if (Input.GetAxisRaw ("Horizontal") < 0)
{
transform.Translate (Vector2.right * velocity * Time.deltaTime);
transform.eulerAngles = new Vector2 (0, 180);
Debug.Log(Input.GetAxisRaw ("Horizontal"));
}
}
// Прыжок персонажа был еще той занозой в заднице
void Jump()
{
if (Input.GetKeyDown(KeyCode.Space) && floortouch.on_floor == true && timer <= 0.0f)
{
rb1.AddForce(Vector2.up * JumpForce, ForceMode2D.Impulse);
floortouch.on_floor = false;
}
else if(Input.GetKeyDown(KeyCode.Space) && floortouch.on_floor == false)
{
rb1.AddForce(Vector2.down * 40, ForceMode2D.Impulse);
floortouch.on_floor = true;
timer = 0.10f;
}
}
}
Answer the question
In order to leave comments, you need to log in
It is not very clear where and when the method is called Punch()
, in theory you have this part
if(Input.GetKeyDown(KeyCode.E))
{
if (hit.collider != null)
{
if(hit.collider.gameObject.CompareTag("enemy"))
{
Debug.Log("enemy");
}
}
}
Update()
, I hope it helped somehow))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question