Good day!
In my 2D platformer I have a flying enemy which is moving with a specific speed left and right.He has a child which is a collider that detects when the player is under the enemy.My enemy is moving using velocty in a FixedUpdate function.
What I want: When the player is behind the enemy , it should attack him by dropping down on him and then go back the initial position and resume the standard movement(left right).I tried by setting the velocity to zero but can’t figure out how does the fixed update is working.
Please tell me exactly what is the best way for doing the behavior of the enemy.
Here is my script:
using UnityEngine;
using System.Collections;
public class FlyingEnemyMove : MonoBehaviour {
public GameObject player;
public float movingSpeed;
private int direction;
public float maxDist;
public float minDist;
// Use this for initialization
void Start ()
{
direction = -1;
maxDist += transform.position.x;
minDist -= transform.position.x;
}
void FixedUpdate()
{
movingLeftAndRight ();
}
void Update ()
{
}
void movingLeftAndRight()
{
switch (direction)
{
case -1:
{
// Moving Left
if( transform.position.x > minDist)
{
GetComponent <Rigidbody2D>().velocity = new Vector2(-movingSpeed,GetComponent<Rigidbody2D>().velocity.y);
}
else
{
direction = 1;
}
break;
}
case 1:
{
//Moving Right
if(transform.position.x < maxDist)
{
GetComponent <Rigidbody2D>().velocity = new Vector2(movingSpeed,GetComponent<Rigidbody2D>().velocity.y);
}
else
{
direction = -1;
}
break;
}
}
}
public void PullTrigger(Collider2D other)
{
if (other.tag == "Player")
{
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
GetComponent<Rigidbody2D>().angularVelocity = 0f;
}
}
}
Thank you very much!