Я не могу найти способ столкнуть игрока с объектами, которые должны остановить игрока.Например, когда я перемещаю игрока к стене деревьев, он просто проходит через них (и слегка отскакивает от выравнивания сетки), как если бы игрок был призраком.
![here is how it would look, aligned with the grid as it should. enter image description here](https://i.stack.imgur.com/NXSPz.png)
![When I try to move the player towards a collider tile, however, this is what happens... enter image description here](https://i.stack.imgur.com/7C8TU.png)
Ниже приведен код, который я использую в отношении движения игрока:
using System.Collections;
using UnityEngine;
public class PlayerMovement : Character {
Direction currentDir;
Vector2 input;
bool IsMoving = false;
Vector3 startpos;
Vector3 endpos;
float t;
public Sprite upsprite;
public Sprite rightsprite;
public Sprite downsprite;
public Sprite leftsprite;
public float walkSpeed = 3f;
public bool isAllowedToMove = true;
private Rigidbody2D myRB;
void Start()
{
isAllowedToMove = true;
myRB = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
protected override void Update () {
if (! IsMoving && isAllowedToMove) {
input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
if (Mathf.Abs(input.x) > Mathf.Abs(input.y))
input.y = 0;
else
input.x = 0;
if (input != Vector2.zero) {
if (input.x < 0) {
currentDir = Direction.Left;
}
if (input.x > 0) {
currentDir = Direction.Right;
}
if (input.y < 0) {
currentDir = Direction.Down;
}
if (input.y > 0) {
currentDir = Direction.Up;
}
switch (currentDir) {
case Direction.Up:
gameObject.GetComponent<SpriteRenderer>().sprite = upsprite;
break;
case Direction.Right:
gameObject.GetComponent<SpriteRenderer>().sprite = rightsprite;
break;
case Direction.Down:
gameObject.GetComponent<SpriteRenderer>().sprite = downsprite;
break;
case Direction.Left:
gameObject.GetComponent<SpriteRenderer>().sprite = leftsprite;
break;
}
StartCoroutine (Move (transform));
}
myRB.velocity = new Vector2 (Input.GetAxisRaw ("Horizontal") * walkSpeed, myRB.velocity.y);
myRB.velocity = new Vector2 (myRB.velocity.x, Input.GetAxisRaw ("Vertical") * walkSpeed);
if (Input.GetAxisRaw ("Horizontal") < 0.5f && Input.GetAxisRaw ("Horizontal") > -0.5f)
{
myRB.velocity = new Vector2 (0f, myRB.velocity.y);
}
if (Input.GetAxisRaw ("Vertical") < 0.5f && Input.GetAxisRaw ("Vertical") > -0.5f)
{
myRB.velocity = new Vector2(myRB.velocity.y, 0f);
}
}
base.Update ();
}
public IEnumerator Move(Transform entity)
{
IsMoving = true;
startpos = entity.position;
t = 0;
endpos = new Vector3(startpos.x + System.Math.Sign(input.x), startpos.y + System.Math.Sign(input.y), startpos.z);
while(t < 1f)
{
t += Time.deltaTime * walkSpeed;
entity.position = Vector3.Lerp(startpos, endpos, t);
yield return null;
}
IsMoving = false;
yield return 0;
}
}
enum Direction
{
Up,
Right,
Down,
Left
}
Следует отметить, что я обязательно использовал Rigidbody2D иВставьте компоненты Collider2D, и я позаботился о том, чтобы сделать для гравитации шкалу 0 для игрока и заморозить вращение от оси Z.Кроме того, я использовал расширения Tiled и Tiled2Unity для создания плиток, которые вы видите в игре, несмотря на то, что предустановленные ресурсы tilemap являются достойным выбором для создания двумерных игровых миров.
Простите, если это кажется слишком длинным, но я могуКажется, не выяснить, в чем проблема с обнаружением столкновений.Кто-нибудь может помочь?