I have an adversary that constantly pursues the player. Everything functions as expected until I use teleportation abilities, after which the enemy’s speed is progressively reduced with each teleport. I’ve observed that the velocity magnitude of the enemy decreases each time I perform a teleportation.
Enemy Movement code:
[SerializeField] public GameObject player;
private Transform playerTransform;
[SerializeField] private float movementSpeed;
private Rigidbody2D rb;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
playerTransform = player.transform;
if (player != null)
{
// Calculate the direction to the player
Vector3 direction = (playerTransform.position - transform.position).normalized;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
rb.rotation = angle;
Vector2 moveDirection = direction;
rb.velocity = moveDirection * movementSpeed;
print(new Vector2(moveDirection.x, moveDirection.y));
}
}
Teleport code:
private Transform player;
private Rigidbody2D rb;
public LayerMask IgnoreMe;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
rb = GameObject.FindGameObjectWithTag("Player").GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (IsRaycastTouchingBorders())
{
StartCoroutine(DelayAction(0.5f));
}
}
}
private void TeleportPlayer()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 newPosition = mousePosition;
// Ensure the new position is not blocked by the "Border" tag before teleporting
if (IsRaycastTouchingBorders())
{
player.position = newPosition;
}
}
public bool IsRaycastTouchingBorders()
{
Vector3 playerPosition = player.position;
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(playerPosition, mousePosition - playerPosition, Vector3.Distance(playerPosition, mousePosition) , ~IgnoreMe);
if (hit.collider != null)
{
if (hit.collider.CompareTag("Border"))
{
return false;
}
}
return true;
}
IEnumerator DelayAction(float delayTime)
{
yield return new WaitForSeconds(delayTime);
TeleportPlayer();
}