По какой-то причине это значение расстояния переключается между исходным значением и новым значением, хотя исходное значение не должно вызываться. Это не проблема, когда NPC достигает конечной точки, и я считаю, что проблема кроется где-то в условии (player != null).
HeroController.cs
Код: Выделить всё
private int direction = 1;
public float changeTime = 3.0f;
float timer;
public UIHandler uiHandler;
public int gold = 10;
public float distanceFromPlayer = 20;
public PlayerController player;
Rigidbody2D rigidbody2d;
Vector2 moveDirection = new Vector2(1,0);
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
rigidbody2d = GetComponent();
timer = changeTime;
}
// Update is called once per frame
void Update()
{
Debug.Log("direction: " + direction);
timer -= Time.deltaTime;
if (timer < 0)
{
timer = changeTime;
}
if (player != null)
{
float distance = Vector2.Distance(transform.position, player.transform.position);
if(distance > distanceFromPlayer && timer == changeTime)
{
spendMoney();
}
}
}
void FixedUpdate()
{
Vector2 position = rigidbody2d.position;
position.x = position.x + speed * direction * Time.deltaTime;
rigidbody2d.MovePosition(position);
}
void OnTriggerEnter2D(Collider2D other)
{
StartPoint startPoint = other.gameObject.GetComponent();
EndPoint endPoint = other.gameObject.GetComponent();
if (startPoint != null)
{
direction=0;
uiHandler.DisplayLoseScreen();
}
if(endPoint != null)
{
direction=-1;
uiHandler.DisplayWinScreen();
}
}
Код: Выделить всё
using UnityEngine;
using UnityEngine.InputSystem;
using System;
public class PlayerController : MonoBehaviour
{
public float speed = 0.1f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
public InputAction MoveAction;
Rigidbody2D rigidbody2d;
Vector2 move;
Vector2 moveDirection = new Vector2(1,0);
void Start()
{
MoveAction.Enable();
rigidbody2d = GetComponent();
}
// Update is called once per frame
void Update()
{
move = MoveAction.ReadValue();
if(!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y,0.0f))
{
moveDirection.Set(move.x, move.y);
moveDirection.Normalize();
}
}
void FixedUpdate()
{
Vector2 position = (Vector2)rigidbody2d.position + move * speed * Time.deltaTime;
rigidbody2d.MovePosition(position);
}
public Vector2 getPosition()
{
return transform.position;
}
}

Подробнее здесь: https://stackoverflow.com/questions/798 ... new-values
Мобильная версия