Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

Make Enemy follow and rotate towards target in Unity

///We shall make the enemy follow the target and then we will make the enemy flip when the target set comes behind the enemy along the x axis
///You can use this script to make an enemy follow the player or to make an object flip towards an object
//For this script to work, you must assign a game object in Unity in the followTarget field.

//Declare Variables
public GameObject followTarget;
public bool _facingRight = false;

void Update()
    {
    	//Makes the game object attached to the script move towards the gameobject set in the followTarget
        transform.position = Vector2.MoveTowards(transform.position, followTarget.transform.position, _moveSpeed* Time.deltaTime);
        
        //Compares the target and the object transform and flips in the direction towards the position that the setTarget is currently at.
        if (followTarget.transform.position.x < gameObject.transform.position.x && _facingRight)
        {
            flip();
        }

        if (followTarget.transform.position.x > gameObject.transform.position.x && !_facingRight)
        {
            flip();
        }
    }
 
    private void flip()
    {
        _facingRight = !_facingRight;
        
        //assigns a the scale component to a variable temporarily
        Vector3 tmpScale = gameObject.transform.localScale;
        tmpScale.x *= -1;
        gameObject.transform.localScale = tmpScale;
    }
Comment

PREVIOUS NEXT
Code Example
Csharp :: set ByteArrayContent content type json 
Csharp :: parent to children nextJs 
Csharp :: wpf stackpanel horizontal 
Csharp :: C# program to find sum of array elements 
Csharp :: what is implicit keyword c# 
Csharp :: [Package Manager Window] Error while fetching labels: User is not logged in or user status invalid. UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&) 
Csharp :: how to navigate between page in wpf 
Csharp :: how to edit a c# list 
Csharp :: classe padre figlio c# 
Csharp :: datareader get field names 
Csharp :: Custom Encrypted String Type 
Csharp :: back color for DateTimePicker control 
Csharp :: C# assign integer 
Csharp :: c# ? behind variable 
Csharp :: external font family uwp c# 
Csharp :: ask int text c# 
Csharp :: 1/1/1/1/1 
Csharp :: SerializedObjectNotCreatableException: Object at index 0 is null 
Csharp :: serenity.is get entity columns as ienumerable string 
Csharp :: when should i use struct rather than class in c# 
Csharp :: c# read file while writing 
Csharp :: Known Folders C# 
Csharp :: google sheets problems cell not considered even 
Csharp :: how to collect input from a user in discord bot c# 
Csharp :: c# with keyword 
Csharp :: asp.net core relative file path within console app 
Csharp :: revision1 
Csharp :: mvc validate 
Csharp :: small index c# 
Csharp :: C# Func Delegate 
ADD CONTENT
Topic
Content
Source link
Name
7+8 =