Jumping system for a 2D enemy
I am trying to create a C# script for a game object that will essentially be an enemy. When an object that has this script attached is near the player, it will jump towards it. I have the following code in my FixedUpdate method:
if (!_hasJumped && RemainingDistanceX < 1.5F)
{
float step = 3F * Time.deltaTime;
_animator.SetTrigger("Jump");
Vector2 jumpLocation = new Vector2(this.transform.position.x, _jumpDistanceOnY);
this.transform.position = Vector2.MoveTowards(this.transform.position, jumpLocation, step);
if (this.transform.position.y == _jumpDistanceOnY)
{
_hasJumped = true;
_animator.SetInteger("AnimState", 0);
}
}
if (_hasJumped)
{
float step = 3F * Time.deltaTime;
Vector2 jumpLocation = new Vector2(this.transform.position.x, _originalPosition.y);
this.transform.position = Vector2.MoveTowards(this.transform.position, jumpLocation, step);
}
The _hasJumped variable is a bool that starts as false. The RemainingDistanceX is a property that returns the distance left to reach the player.
This is what I have in my Start method:
void Start()
{
_jumpDistanceOnY = this.transform.position.y + 0.75F;
_originalPosition = new Vector2(this.transform.position.x, this.transform.position.y);
_currentHealth = maxHealth;
_animator = GetComponentInChildren<Animator>();
_seeker = GetComponent<Seeker>();
_rigidbody = GetComponent<Rigidbody2D>();
_audioManager = FindObjectOfType<AudioManager>();
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);
}
I should mention that I've locked on the Y axis the Rigidbody component for this object. This code is working (object is jumping up and then returning to its initial Y coordinate), however, my issue here is that I can't figure out how to move this object around on the X axis since I can't do any calculation on the position in the FixedUpdate without breaking it (the object staying on the Y axis at the new coordinates or just not performing the "jump" at all). Right now, I am only trying to make it jump 0.5F towards the player and then return to the original Y coordinate by either falling on the Y or moving an addition 0.5F while falling. Any ideas on how I can move this object around in FixedUpdate or maybe another way?