So i made this one C# script about the movement of the character (I’m a beginner) and i came across this issue with ray casting.
Sometimes when i ray cast it detects the player (after I modify the script)
Sometimes it doesn’t detect anything (after I modify the script)
Here’s the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement1 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Camera.main.transform.position = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y,-10);
if (Input.GetKey(KeyCode.RightArrow))
{
//weapon stuff here
if (GetComponent<Rigidbody2D>())
{
GetComponent<Rigidbody2D>().velocity = GetComponent<Rigidbody2D>().velocity + new Vector2(0.3f, 0);
gameObject.transform.localScale = new Vector2(0.4f, 0.4f);
}
}
if (Input.GetKey(KeyCode.LeftArrow))
{
if (GetComponent<Rigidbody2D>())
{
GetComponent<Rigidbody2D>().velocity = GetComponent<Rigidbody2D>().velocity + new Vector2(-0.3f, 0);
gameObject.transform.localScale = new Vector2(-0.4f, 0.4f);
}
}
if (Input.GetKeyDown(KeyCode.Z))
{
//weapon stuff here
if (GetComponent<Rigidbody2D>())
{
LayerMask mask = LayerMask.NameToLayer("Default");
RaycastHit2D hitd = Physics2D.Raycast(transform.position, new Vector2(0,-1),-1,mask);
Debug.Log(mask);
if (hitd.collider == null)
{
Debug.Log("Cant find floor");
}
else
{
Debug.Log(hitd.collider.name);
// Raycast(gameObject.transform.position, new Vector2(0,-1), null, null, 5);
GetComponent<Rigidbody2D>().velocity = GetComponent<Rigidbody2D>().velocity + new Vector2(0, 10);
}
}
}
}
}