I was working on a script where, if you click the right arrow, the player moves at a constant speed towards the right side of the screen, then stops after leaving the screen. (Similarly, if you click the left arrow, the player moves at a constant speed towards the left side of the screen, then stops after leaving the screen.)
However, after I added the code, I encountered a problem where the player was moving very slowly, little by little. Additionally, I'm not sure if my code is concise.
I used a while loop to move the player to the target position, but the code severely overloaded the computer, forcing me to close Unity. I'm worried that this will cause problems with the computer. The code caused severe lag, and I have no idea what is causing it. Please help me...
Here is my code:(Logic includes moving with direction keys)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerManager : MonoBehaviour
{
public float speed = 500f;
public float runSpeed = 200f;
public GameObject player;
public GameObject rightArrow;
public GameObject leftArrow;
private Vector2 movement;
private bool isRunning;
private Animator anim;
private Rigidbody2D rb;
private void Start()
{
anim = player.GetComponent<Animator>();
rb = player.GetComponent<Rigidbody2D>();
}
private void Update()
{
// Get input
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
isRunning = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
if (Input.GetMouseButtonDown(0))
{
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);
if (hit.collider != null)
{
if (hit.collider.gameObject == rightArrow)
{
int clickX = 1;
ArrowClick(clickX);
}
else if (hit.collider.gameObject == leftArrow)
{
int clickX = -1;
ArrowClick(clickX);
}
}
}
}
public void ArrowClick(int _clickX)
{
Vector2 target = new Vector2(100 * _clickX, 0);
while (true)
{
player.transform.position
= Vector2.MoveTowards(player.transform.position, target, 10);
}
}
private void FixedUpdate()
{
// Move the character
float currentSpeed = isRunning ? speed * runSpeed : speed;
Vector2 velocity = movement.normalized * currentSpeed;
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
private void LateUpdate()
{
// Update animator
anim.SetFloat("DirX", movement.x);
anim.SetFloat("DirY", movement.y);
anim.SetBool("Idle", movement.magnitude == 0);
}
}