Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Can't stop enemy from leaning forward

Discussion in 'Scripting' started by Saint503, Jan 5, 2018.

  1. Saint503

    Saint503

    Joined:
    Jan 5, 2018
    Posts:
    3
    I've found a few threads with answers but I'm not able to implement them into my code.

    I have enemies that will follow the player but they lean forward or lean back depending on their distance. How can I freeze the rotation?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class EnemyController : MonoBehaviour
    6. {
    7.     private Rigidbody myRB;
    8.     public float moveSpeed;
    9.  
    10.     public PlayerController thePlayer;
    11.    
    12.     // Use this for initialization
    13.     void Start ()
    14.     {
    15.      
    16.        
    17.         myRB = GetComponent<Rigidbody>();
    18.         thePlayer = FindObjectOfType<PlayerController>();
    19.  
    20.     }
    21.  
    22.     private void FixedUpdate()
    23.     {
    24.         myRB.velocity = (transform.forward * moveSpeed);
    25.     }
    26.     // Update is called once per frame
    27.     void Update ()
    28.     {
    29.  
    30.         transform.LookAt(thePlayer.transform.position);
    31.        
    32.      
    33.     }
    34. }
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    You don't want to lookat in the y direction so it's:

    Code (csharp):
    1.  
    2. Vector3 lookPos = thePlayer.transform.position;
    3. lookPos.y = transform.position.y;
    4. transform.LookAt(lookPos);
    5.  
     
    Last edited: Jan 5, 2018
    Saint503 likes this.
  3. Saint503

    Saint503

    Joined:
    Jan 5, 2018
    Posts:
    3
    thank you so much. this worked perfect.
     
  4. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    Glad it worked out.