I wish to make a script where the player sprite moves around and when it touches specific objects it stops while when it touches others it moves past them. this can be done with oncollisionenter or ontriggerenter but this is a something I want to do with purely scripting and no other components other than colliders.
my current way of doing this is casting 5 rays in the direction the sprite is moving and act according to what is in front. my problem is that I cannot calculate the way to make 5 rays appear in every direction (8 directions including the diagonals because that is how my game works). this is the basic idea that I have:
public float Speed;
public Transform PlayerTransform;
public Sprite PlayerCharacter;
LayerMask lm = new LayerMask();
RaycastHit2D[] ForwardRay = new RaycastHit2D[5];
Vector2 dir;
int verticalMov = 1;
int horizontalMov = 0;
void Update()
{
if (Input.GetKey(Up)) verticalMov++; // keys pressed
if (Input.GetKey(Down)) verticalMov--;
if (Input.GetKey(Left)) horizontalMov--;
if (Input.GetKey(Right)) horizontalMov++;
dir = new Vector2(horizontalMov, verticalMov); // calculate direction of movement
ForwardRay = new RaycastHit2D[5];
int j = 0;
for (int i = ForwardRay.Length / -2; i < ForwardRay.Length / 2 + 0.5; i++)
{
ForwardRay[j] = Physics2D.Raycast(new Vector2(PlayerTransform.position.x + (PlayerCharacter.bounds.size.x / (ForwardRay.Length - 1) * i * dir.x), PlayerTransform.position.y + (PlayerCharacter.bounds.size.y / (ForwardRay.Length - 1) * i * dir.y)), dir, 0.5f, lm); // calculation that does not work
Debug.DrawRay(new Vector2(PlayerTransform.position.x + (PlayerCharacter.bounds.size.x / (ForwardRay.Length - 1) * i), PlayerTransform.position.y + (PlayerCharacter.bounds.size.y / (ForwardRay.Length - 1) * i)), dir, Color.red, Mathf.Infinity); // debugging
if (ForwardRay[j] && ForwardRay[j].collider)
{
if (ForwardRay[j].collider.gameObject.layer == 7)
{
dir = Vector2.zero; // stop moving if hit an obstacle
}
}
j++;
}
PlayerTransform.Translate(dir.normalized * Speed * Time.deltaTime); // calculate movement
}
my problem is that I cannot find a way to calculate and cast the 5 rays in all 8 directions the player can point to. if anyone has any ideas or answers please help.