Почему мое направление переключается между исходным и новым значениями? [закрыто]C#

Место общения программистов C#
Ответить
Anonymous
 Почему мое направление переключается между исходным и новым значениями? [закрыто]

Сообщение Anonymous »

Я пытаюсь заставить NPC менять направление x на прямом пути, когда у него заканчиваются деньги после превышения определенного расстояния от игрока.
Это значение расстояния переключается между исходным и новым значением, даже если исходное значение не следует вызывать. Это не проблема, когда NPC достигает конечной точки при инициализации OnTriggerEnter2D. Я считаю, что проблема заключается в условии (player != null).
NPCController.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();
}
}
PlayerController.cs:

Код: Выделить всё

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
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»