- Home /
Question by
whatisitstudios_unity · Jan 24, 2021 at 08:40 PM ·
2denemypathfindingplatformerenemy ai
Why is my gameObject falling so slow?
I was testing out my own pathfinding script, and it worked, but only on the x axis, whenever the enemy falls, he falls super slowly, while all the other objects fall normally, could someone tell my why? I gravity turned on in the rigidbody menu, and it's the same speed as everything else, so i don't know why it does this.
Here's my code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class SlimePathfinding : MonoBehaviour
{
public float speed = 5f;
public Transform target;
public Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
Vector2 currentPos = transform.position;
Vector3 Scaler = transform.localScale;
if (target.position.x > currentPos.x)
{
Scaler.x = -1;
transform.localScale = Scaler;
rb.velocity = transform.right * speed;
}
else
{
Scaler.x = 1;
transform.localScale = Scaler;
rb.velocity = transform.right * -1 * speed;
}
}
}
Comment
Answer by Tespy · Jan 25, 2021 at 12:42 AM
It's because you're setting the y velocity of the enemy to 0, which conflicts with how Unity's physics system updates the velocity. I don't know the details of how that works, but this rewritten Update should fix your issue:
void Update()
{
Vector2 currentPos = transform.position;
Vector3 Scaler = transform.localScale;
Vector2 velocity = rb.velocity; // Original velocity
// The following if statements make it so the original velocity
// (as set by the physics system) is preserved, albeit with only
// the movement on the x axis changed.
if (target.position.x > currentPos.x)
{
Scaler.x = -1;
transform.localScale = Scaler;
velocity.x = speed;
}
else
{
Scaler.x = 1;
transform.localScale = Scaler;
velocity.x = -speed;
}
rb.velocity = velocity; // With the new velocity decided, apply it to the Rigidbody2D
}