Search Unity

How to make a random moving enemy move with the Camera[Doodle Jump like game]?

Discussion in '2D' started by abatmanxo, Nov 23, 2019.

  1. abatmanxo

    abatmanxo

    Joined:
    Nov 23, 2019
    Posts:
    1
    ENEMY FOLLOW --

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class EnemyFollow : MonoBehaviour
    6. {
    7.     public Transform enemy;
    8.  
    9.     void Update()
    10.     {
    11.         if(enemy.position.y > transform.position.y){
    12.  
    13.             Vector3 newPos1 = new Vector3(transform.position.x, enemy.position.y, transform.position.z);
    14.             transform.position = newPos1;
    15.         }  
    16.     }
    17. }
    ENEMY --

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Enemy : MonoBehaviour
    6. {
    7.     public float speed = 1.5f;
    8.     public float rotateSpeed = 5.0f;
    9.     Vector3 newPosition;
    10.     bool isMoving = false;
    11.    
    12.     public GameObject player;
    13.  
    14.     void Start ()
    15.     {
    16.         PositionChange();
    17.     }
    18.     void PositionChange()
    19.     {
    20.         newPosition = new Vector2(Random.Range(-5.0f, 5.0f), Random.Range(-5.0f, 5.0f));
    21.     }
    22.  
    23.     void Update ()
    24.     {
    25.         if(Vector2.Distance(transform.position, newPosition) < 1)
    26.             PositionChange();
    27.         if(LookAt2D(newPosition))
    28.             transform.position=Vector3.Lerp(transform.position,newPosition,Time.deltaTime*speed);
    29.     }
    30.     bool LookAt2D(Vector3 lookAtPosition)
    31.     {
    32.         float distanceX = lookAtPosition.x - transform.position.x;
    33.         float distanceY = lookAtPosition.y - transform.position.y;
    34.         float angle = Mathf.Atan2(distanceX, distanceY) * Mathf.Rad2Deg;
    35.      
    36.         Quaternion endRotation = Quaternion.AngleAxis(angle, Vector3.back);
    37.         transform.rotation = Quaternion.Slerp(transform.rotation, endRotation, Time.deltaTime * rotateSpeed);
    38.         if(Quaternion.Angle(transform.rotation, endRotation) < 1f)
    39.             return true;
    40.         return false;
    41.     }
    42.     private void OnTriggerEnter2D(Collider2D collision) {
    43.  
    44.         Destroy(collision.gameObject);
    45.     }
    46. }
    47.