I'm working on a 2d platformer, and originally I had enemies move between two box colliders, turning whenever it triggers one. This worked... until it didn't, so I looked up a tutorial for enemy movement. I came across [this video][1] and it looked great! I copied what they did line for line, but when I tested it... [this happened (sorry for the poor quality!)][2]
After taking a closer look, I realized one of the problems was with the scaling. At the bottom of my script are these lines:
private void OnTriggerExit2D(Collider2D col)
{
//Turn
transform.localScale = new Vector2(-(Mathf.Sign(rb.velocity.x)), transform.localScale.y);
}
I think the problem here is that me enemy isn't at a scale of 1, which mathF stands for, apparently. So I then tried this out:
private void OnTriggerExit2D(Collider2D col)
{
//Turn
transform.localScale = new Vector2(-transform.localScale.x, transform.localScale.y);
}
So now it doesn't grow, but it still won't move! Also it turns around instantly... I'm genuinely unsure what to do now, so if you guys have ANY ideas, it would be greatly appreciated!
One more thing, here's the entire script!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public Rigidbody2D rb;
[SerializeField]
bool touchingGround = false;
[SerializeField]
float speed = 0f;
void Start()
{
rb = GetComponent();
}
void Update()
{
if (IsFacingRight())
{
//Move right
rb.velocity = new Vector2(speed, 0f);
}
else
{
//Take it back now yall (left, move left)
rb.velocity = new Vector2(-speed, 0f);
}
}
private bool IsFacingRight()
{
return transform.localScale.x > Mathf.Epsilon;
}
private void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.CompareTag("bullet"))
{
Destroy(gameObject);
}
if (col.gameObject.CompareTag("ground"))
{
touchingGround = true;
}
if (col.gameObject.CompareTag("tree"))
{
touchingGround = true;
}
}
private void OnTriggerExit2D(Collider2D col)
{
//Turn
transform.localScale = new Vector2(-transform.localScale.x, transform.localScale.y);
}
}
[1]: https://www.youtube.com/watch?v=MPnN9i1SD6g&t=456s
[2]: https://youtu.be/LYQ0SuK5u5M
↧