Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Moving enemy script.

Discussion in 'Scripting' started by Woleth, Jan 25, 2018.

  1. Woleth

    Woleth

    Joined:
    Jan 22, 2018
    Posts:
    6
    I made the enemies in my game follow the player but I needed also that they were capable of rotating at the same time they are turning to the player position so I came up with this:

    Code (CSharp):
    1.     void FixedUpdate () {
    2.  
    3.         if (Input.GetAxis ("Horizontal") == 1) {
    4.             enemyRigidbody.AddRelativeTorque (0f, 0f, 3f);
    5.         }
    6.  
    7.         if (Input.GetAxis ("Horizontal") == -1) {
    8.             enemyRigidbody.AddRelativeTorque (0f, 0f, -3f);
    9.         }
    10.  
    11.         if (Input.GetAxis ("Horizontal") == 0) {
    12.             enemyRigidbody.angularVelocity = Vector3.zero;
    13.         }
    The problem is it doesn't work, although is the same code that I wrote on the player movement script, and I don't know why.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class EnemyController : MonoBehaviour {
    5.  
    6.     private Rigidbody enemyRigidbody;
    7.     public PlayerController player;
    8.     public float moveSpeed;
    9.     public EnemyGunController gun;
    10.     public Vector3 rotateSpeed;
    11.  
    12.     // Use this for initialization
    13.     void Start () {
    14.         enemyRigidbody = GetComponent<Rigidbody> ();
    15.         player = FindObjectOfType<PlayerController> ();
    16.     }
    17.    
    18.     // Update is called once per frame
    19.     void Update () {
    20.        
    21.     }
    22.  
    23.     void FixedUpdate () {
    24.         transform.LookAt (player.transform.position);
    25.  
    26.         if (Input.GetAxis ("Horizontal") == 1) {
    27.             enemyRigidbody.AddRelativeTorque (0f, 0f, 3f);
    28.         }
    29.  
    30.         if (Input.GetAxis ("Horizontal") == -1) {
    31.             enemyRigidbody.AddRelativeTorque (0f, 0f, -3f);
    32.         }
    33.  
    34.         if (Input.GetAxis ("Horizontal") == 0) {
    35.             enemyRigidbody.angularVelocity = Vector3.zero;
    36.         }
    37.  
    38.         if (transform.position.sqrMagnitude >= (player.transform.position.sqrMagnitude - 150)) {
    39.             enemyRigidbody.velocity = transform.forward * moveSpeed * 0.4f;
    40.             gun.isFiring = true;
    41.         } else {
    42.             enemyRigidbody.velocity = transform.forward * moveSpeed;
    43.             gun.isFiring = false;
    44.         }
    45.            
    46.     }
    47. }