Некоторая информация из текстового файла Pacmangridmover.cs < /p>
Найденное: Maze
Pac -Man, снятый в положении сетки (11, -3)
Pacman, начинается в позиции: (11, -3) < /p>
Это означает, что Pac -Mane -Pace -Paiste -Table -Way. правильно. Более 200 действительных положений перечислены. < /P>
Движение: < /p>
КЛЮЧ. успешно.
Так что это не логическая проблема - это, возможно, это недоразумение визуального/игрового процесса, но я не могу найти в редакторе. Update () < /p>
transform.position = Vector2.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
< /code>
Но код никогда не достигает его, и я проверял с точками останова, что входы клавиш работают. < /p>
Скриншоты: < /p>
Настройки Pacman в Inspector, прежде чем запустить игру: < /p>
Настройки Sprite Pacman Sprite в инспекторе:
{cell} => {prefab.name} at {pos}");
}
if (IsValidWaypoint(x, y))
{
GameObject wp = Instantiate(waypointPrefab, pos, Quaternion.identity, transform);
wp.name = $"Waypoint_{x}_{y}";
Log($"Waypoint created: {wp.name} at {pos}");
}
}
}
}
void Log(string msg)
{
if (msg == lastLog) return;
lastLog = msg;
Debug.Log(msg);
mazeLog.WriteLine($"[{DateTime.Now:HH:mm:ss}] {msg}");
}
bool IsPathCell(char c) => c == '.' || c == 'P' || c == ' ';
bool IsWalkable(int x, int y)
{
if (y < 0 || y >= layout.Length || x < 0 || x >= layout[0].Length)
return false;
return IsPathCell(layout[y][x]);
}
bool IsValidWaypoint(int x, int y)
{
if (!IsWalkable(x, y)) return false;
if ((x >= 10 && x = 11 && y = 23 && x = 10 && y = 23 && x = 16 && y = 0 && x = 10 && y = 0 && x = 16 && y = 3) return true;
if (count == 2 && ((up && right) || (up && left) || (down && right) || (down && left))) return true;
return false;
}
}
< /code>
и сценарий Pacmangridmover: < /p>
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class PacManGridMover : MonoBehaviour
{
public float moveSpeed = 5f;
private Vector2Int currentGridPos;
private Vector2Int targetGridPos;
private Vector2 moveDir = Vector2.zero;
private Vector2 nextMoveDir = Vector2.zero;
private Dictionary waypointDict;
private StreamWriter logWriter;
private string lastLog = "";
void Start()
{
logWriter = new StreamWriter(@"D:\PacManLog.txt", true);
Log("=== PacMan Start ===");
var maze = GameObject.Find("Maze");
Log("Maze found: " + maze?.name);
waypointDict = new Dictionary();
foreach (Transform child in maze.transform)
{
if (child.name.StartsWith("Waypoint"))
{
Vector2Int gridPos = Vector2Int.RoundToInt(child.position);
if (!waypointDict.ContainsKey(gridPos))
{
waypointDict.Add(gridPos, child);
Log($"Added waypoint: {gridPos}");
}
}
}
Vector2Int nearestWaypoint = FindClosestWaypoint(transform.position);
if (waypointDict.ContainsKey(nearestWaypoint))
{
currentGridPos = targetGridPos = nearestWaypoint;
transform.position = new Vector3(waypointDict[nearestWaypoint].position.x, waypointDict[nearestWaypoint].position.y, -1f);
Log($"Pac-Man snapped to grid: {nearestWaypoint}");
}
else
{
Log("No waypoint found. Pac-Man disabled.");
enabled = false;
}
Log("Initial position: " + transform.position);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.UpArrow)) { nextMoveDir = Vector2.up; Log("Key Pressed: Up"); }
if (Input.GetKeyDown(KeyCode.DownArrow)) { nextMoveDir = Vector2.down; Log("Key Pressed: Down"); }
if (Input.GetKeyDown(KeyCode.LeftArrow)) { nextMoveDir = Vector2.left; Log("Key Pressed: Left"); }
if (Input.GetKeyDown(KeyCode.RightArrow)) { nextMoveDir = Vector2.right; Log("Key Pressed: Right"); }
if (ReachedTarget())
{
Vector2Int[] directions = { Vector2Int.up, Vector2Int.down, Vector2Int.left, Vector2Int.right };
foreach (Vector2Int dir in directions)
{
if (Vector2Int.RoundToInt(nextMoveDir) == dir)
{
Vector2Int neighbor = currentGridPos + dir;
if (waypointDict.ContainsKey(neighbor))
{
moveDir = dir;
targetGridPos = neighbor;
Log($"Moving to {neighbor} via {dir}");
break;
}
}
}
if (moveDir != Vector2.zero)
{
Vector2Int forward = currentGridPos + Vector2Int.RoundToInt(moveDir);
if (waypointDict.ContainsKey(forward))
{
targetGridPos = forward;
Log("Continuing to " + forward);
}
else
{
Log("Hit wall. Stop.");
moveDir = Vector2.zero;
}
}
}
if (moveDir != Vector2.zero)
{
Vector2 targetPos = waypointDict[targetGridPos].position;
transform.position = Vector2.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
if (ReachedTarget())
{
currentGridPos = targetGridPos;
Log("Reached: " + currentGridPos);
}
}
}
bool ReachedTarget()
{
if (!waypointDict.ContainsKey(targetGridPos))
{
Log($"Invalid target: {targetGridPos}");
return false;
}
Vector2 pac = transform.position;
Vector2 target = waypointDict[targetGridPos].position;
float distance = Vector2.Distance(pac, target);
bool reached = distance < 0.15f;
Log($"Checking target. Dist: {distance:F3}, Reached: {reached}");
return reached;
}
Vector2Int FindClosestWaypoint(Vector3 position)
{
Vector2Int closest = new();
float minDist = float.MaxValue;
foreach (var pair in waypointDict)
{
float dist = Vector2.Distance(position, pair.Value.position);
if (dist < minDist)
{
minDist = dist;
closest = pair.Key;
}
}
Log("Closest waypoint: " + closest);
return closest;
}
void Log(string message)
{
if (message == lastLog) return;
lastLog = message;
Debug.Log(message);
logWriter.WriteLine($"[{DateTime.Now:HH:mm:ss}] {message}");
logWriter.Flush();
}
void OnDestroy()
{
logWriter?.Close();
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... -the-pacma
В то время как в текстовом файле журнала он показывает, что Pacman переехал в редактор, Pacman никогда не меняет позицию ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как создать редактор JavaScript, редактор HTML и редактор CSS в HTML?
Anonymous » » в форуме Android - 0 Ответы
- 51 Просмотры
-
Последнее сообщение Anonymous
-