Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class RunAwayEnemi : MonoBehaviour
- {
- public int speedX = 0;
- public int speedY = 0;
- private float generalSpeed = 0.014f;
- private Animator animController = null;
- private Character character = null; //character este personaje
- public GameObject Enemi = null;
- public Character EnemiCharacter = null; //character del target
- // Use this for initialization
- void Start ()
- {
- animController = this.GetComponent<Animator>();
- character = this.GetComponent<Character>();
- Enemi = GameObject.Find("Principal");
- //target != null
- if (Enemi)
- {
- EnemiCharacter = Enemi.GetComponent<Character>();
- }
- else
- {
- Debug.LogError("Enemi is NULL");
- }
- generalSpeed += Random.Range(-0.004f, 0.004f);
- }
- // Update is called once per frame
- void Update()
- {
- //if (target != null && targetCharacter != null && character != null && character.GetIsAlive())
- if (Enemi && EnemiCharacter && character && character.GetIsAlive())
- {
- UpdateMovementDirectionByEnemi();
- }
- else
- {
- speedX = 0;
- speedY = 0;
- }
- UpdateAnimation();
- UpdatePosition();
- }
- void UpdateMovementDirectionByEnemi()
- {
- //Vivo
- if (EnemiCharacter.GetIsAlive())
- {
- Vector3 currentPos = this.transform.position;
- Vector3 EnemiPos = Enemi.transform.position;
- Vector3 deltaPos;
- deltaPos.x = EnemiPos.x - transform.position.x;
- deltaPos.y = EnemiPos.y - currentPos.y;
- float margin = generalSpeed * 2 + 0.2f;
- // Eje X
- if (deltaPos.x > margin)
- {
- speedX = 1;
- }
- else if (deltaPos.x < -margin)
- {
- speedX = -1;
- }
- else
- {
- speedX = 0;
- }
- // Eje Y
- if (deltaPos.y > margin)
- {
- speedY = 1;
- }
- else if (deltaPos.y < -margin)
- {
- speedY = -1;
- }
- else
- {
- speedY = 0;
- }
- }
- else
- {
- speedX = 0;
- speedY = 0;
- }
- private void UpdateAnimation()
- {
- if (animController)
- {
- animController.SetInteger("speedX", speedX);
- animController.SetInteger("speedY", speedY);
- }
- else
- {
- Debug.LogError("animController is NULL");
- }
- }
- private void UpdatePosition()
- {
- Vector2 currentSpeed;
- currentSpeed.x = speedX;
- currentSpeed.y = speedY;
- //Transformarlo en unitario
- currentSpeed.Normalize();
- //Le damos magnitud
- currentSpeed *= generalSpeed;
- //Hacemos el cambio de posición
- Vector3 currentPos = transform.position;
- currentPos.x += currentSpeed.x;
- currentPos.y += currentSpeed.y;
- transform.position = currentPos;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement