New to Unity in that I’m finally making small games with having to look at tutorials constantly! So proud of that, but currently stuck with this issue that I can’t seem to wrap my head around. I have it so when my player walks into an enemy collider, the player stops and the enemy walks over to the player to begin battle. The issue is that when the enemy gets to the player it starts jittering. and even when I set moveEnemy = false; (if directionToPlayer.x = 0 or something) it still won’t stop. Any help would be greatly appreciated!
I know… I need to get better about use code tags. I always think about them as I’m writing a script and am like “ill set it after this!” and then I forget, it’s a bad habit I’m working on while programming.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerMovement : MonoBehaviour
{
private Vector2 movement;
private Rigidbody2D playerRB;
public float speed = 5f;
public Animator animator;
//public Animator transitionLevel;
public float transistionTime = 10f;
private bool canMove = true;
// Start is called before the first frame update
void Start()
{
canMove = true;
animator.SetBool("isActive", true);
playerRB = GetComponent<Rigidbody2D>();
animator.SetFloat("LastVertical", -1);
}
// Update is called once per frame
void Update()
{
if (canMove)
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
animator.SetFloat("Horizontal", movement.x);
animator.SetFloat("Vertical", movement.y);
animator.SetFloat("Speed", movement.sqrMagnitude);
if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0)
{
animator.SetFloat("LastHorizontal", Input.GetAxisRaw("Horizontal"));
animator.SetFloat("LastVertical", Input.GetAxisRaw("Vertical"));
}
} else
{
animator.SetFloat("LastHorizontal", 0);
animator.SetFloat("LastVertical", -1);
animator.SetFloat("Speed", 0);
}
}
private void FixedUpdate()
{
if (canMove)
{
Vector2 moveHorizontal = transform.right * movement.x;
Vector2 moveVertical = transform.up * movement.y;
Vector2 velocity = ((moveHorizontal + moveVertical).normalized * speed);
playerRB.MovePosition(playerRB.position + velocity * Time.fixedDeltaTime);
}
}
private IEnumerator OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name.Equals("LevelEnemy"))
{
canMove = false;
yield return new WaitForSeconds(.5f);
StartCoroutine(LoadLevel("FightScene"));
}
}
IEnumerator LoadLevel(string LevelName)
{
//transitionLevel.SetTrigger("Start");
yield return new WaitForSeconds(transistionTime);
LevelLoader.levelToLoad = "FightScene";
LevelLoader.timeToTransistion = true;
}
public void setMovementBool(bool isItTrue)
{
canMove = isItTrue;
}
}
I figured it out! Since I have the player object stand still once seen, I use the lerp function. Let me know if there’s a better solution! but so far happy with this!