Question by
Sayden96 · Mar 29, 2020 at 03:48 PM ·
c#script.charactercontrollercontroller
The code does not work in unity
I have a code with 0 errors but when applying it in the sprite in unity nothing happens absolutely.
The code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyScript : MonoBehaviour
{
[SerializeField]
Transform castPoint;
[SerializeField]
Transform player;
[SerializeField]
float agroRange;
[SerializeField]
float moveSpeed;
Rigidbody2D rb2d;
Animator animator;
bool isFacingLeft;
private bool isAgro = false;
private bool isSearching;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if(CanSeePlayer(agroRange))
{
isAgro = true;
}
else
{
if(isAgro)
{
if(!isSearching)
{
isSearching = true;
Invoke("StopChasingPlayer", 5);
}
}
}
if(isAgro)
{
ChasePlayer();
}
}
bool CanSeePlayer(float distance)
{
bool val = false;
float castDist = distance;
if(isFacingLeft)
{
castDist = -distance;
}
Vector2 endPos = castPoint.position + Vector3.right * castDist;
RaycastHit2D hit = Physics2D.Linecast(castPoint.position, endPos, 1 << LayerMask.NameToLayer("Action"));
if(hit.collider != null)
{
if (hit.collider.gameObject.CompareTag("Player"))
{
val = true;
}
else
{
val = false;
}
Debug.DrawLine(castPoint.position, hit.point, Color.yellow);
}
else
{
Debug.DrawLine(castPoint.position, endPos, Color.blue);
}
return val;
}
void ChasePlayer()
{
if(transform.position.x < player.position.x)
{
//enemy is to the left side of the player, so move right
rb2d.velocity = new Vector2(moveSpeed, 0);
transform.localScale = new Vector2(0.60343f, 0.60343f);
isFacingLeft = false;
}
else
{
//enemy is to the right side of the player, so move left
rb2d.velocity = new Vector2(-moveSpeed, 0);
transform.localScale = new Vector2(-0.60343f, 0.60343f);
isFacingLeft = true;
}
animator.Play("Skull_awake");
}
void StopChasingPlayer()
{
isAgro = false;
isSearching = false;
rb2d.velocity = new Vector2(0, 0);
animator.Play("Skull_idle");
}
}
game.png
(505.4 kB)
Comment