To make the player’s interaction a unit test code, I wrote as follows.
We also recognize situations that we shouldn’t recognize.
Sometimes they succeed, and most of them fail.
[UnityTest]
public IEnumerator TestPlayerInteractionFail()
{
_playerObject = new GameObject("Player");
_player = _playerObject.AddComponent<TopDownPlayer>();
_player.transform.position = Vector3.zero;
_interaction = new TopDownInteraction(_player.transform, LayerMask.GetMask("Object"), 1f);
GameObject interactionObject = new GameObject("InteractionTestObject");
interactionObject.AddComponent<CircleCollider2D>();
interactionObject.AddComponent<NpcInteraction>();
interactionObject.layer = LayerMask.NameToLayer("Object");
interactionObject.transform.position = new Vector3(1.0f, 0.0f, 0.0f);
Assert.IsFalse(_interaction.Interact(Vector2.left));
GameObject.DestroyImmediate(interactionObject);
yield return null;
}
using Runtime.CH1.Main.PlayerFunction;
using System;
using UnityEngine;
using UnityEngine.InputSystem;
namespace Runtime.CH1.Main
{
[RequireComponent(typeof(Animator))]
public class TopDownPlayer : MonoBehaviour
{
// TODO 이거 데이터로 빼야함
[SerializeField] private float moveSpeed = 5.0f;
[SerializeField] private float animSpeed = 0.5f;
private Vector2 _movementInput;
private TopDownMovement _movement;
private TopDownAnimation _animation;
private TopDownInteraction _interaction;
private const string Interaction = "Object";
private void Awake()
{
_movement = new TopDownMovement(moveSpeed, transform);
_animation = new TopDownAnimation(GetComponent<Animator>(), animSpeed);
_interaction = new TopDownInteraction(transform, LayerMask.GetMask(Interaction));
}
private void Update()
{
_animation.SetMovementAnimation(_movementInput);
}
private void FixedUpdate()
{
_movement.Move(_movementInput);
}
private void OnMove(InputValue value)
{
_movementInput = value.Get<Vector2>();
}
private void OnInteraction()
{
Debug.Log("Interaction"+_movement.Direction);
_interaction.Interact(_movement.Direction);
}
}
}
using Runtime.CH1.Main.Interface;
using UnityEngine;
namespace Runtime.CH1.Main.PlayerFunction
{
public class TopDownInteraction
{
private readonly Transform _transform;
private readonly int _interactionLayerMask;
private readonly float _interactionDistance;
public TopDownInteraction(Transform transform, int interactionLayerMask, float interactionDistance = 1.0f)
{
_transform = transform;
_interactionLayerMask = interactionLayerMask;
_interactionDistance = interactionDistance;
}
public bool Interact(Vector2 direction)
{
RaycastHit2D hit = Physics2D.Raycast(_transform.position, direction, _interactionDistance, _interactionLayerMask);
if (hit.collider != null)
{
hit.collider.GetComponent<IInteractive>()?.Interact();
return true;
}
return false;
}
}
}