[英]Unity 2D : Collisions detection
我正在嘗試制作Pokemon游戲,但是碰撞檢測有問題。 例如,如果我想在這里右轉:
我應該能夠做到,但是我不能動。 這兩個對象都有BoxCollider2D。 這是播放器的BoxCollider:
樹上有一個boxcollider,大小為1,偏移量為0,0。
這是我的代碼:
void Update()
{
input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
actualSpeed = Input.GetKey(KeyCode.LeftShift) ? walkingVelocity : runingVelocity;
if (input != Vector2.zero && p == transform.position)
{
anim.SetBool("isMoving", true);
if (Mathf.Abs(input.x) > Mathf.Abs(input.y))
{
if (input.x > 0)
{
if (direction.Equals(Direction.Este) && canMove())
{
p += Vector3.right;
}else
{
direction = Direction.Este;
}
}
else
{
if (direction.Equals(Direction.Oeste) && canMove()) {
p -= Vector3.right;
}
else{
direction = Direction.Oeste;
}
}
}
else
{
if (input.y > 0)
{
if (direction.Equals(Direction.Norte) && canMove())
{
p += Vector3.up;
}else
{
direction = Direction.Norte;
}
}
else
{
if (direction.Equals(Direction.Sur) && canMove())
{
p -= Vector3.up;
}
else
{
direction = Direction.Sur;
}
}
}
anim.SetFloat("input_x", input.x);
anim.SetFloat("input_y", input.y);
}
else if (input == Vector2.zero)
{
anim.SetBool("isMoving", false);
}
transform.position = Vector3.MoveTowards(transform.position, p, actualSpeed * Time.deltaTime);
}
bool canMove()
{
bool b = true;
Ray2D r;
if (direction.Equals(Direction.Norte))
{
r = new Ray2D(transform.position, Vector3.up);
}
else if (direction.Equals(Direction.Sur))
{
r = new Ray2D(transform.position, Vector3.down);
}
else if (direction.Equals(Direction.Este))
{
r = new Ray2D(transform.position, Vector3.right);
}
else
{
r = new Ray2D(transform.position, Vector3.left);
}
Debug.DrawRay(r.origin, r.direction);
RaycastHit2D hit = Physics2D.Raycast(r.origin, r.direction, 1f , 1 << 8);
if (hit.collider != null)
{
if (hit.collider.CompareTag("Obstacle"))
{
b = false;
}
}
return b;
}
我如何使玩家移到樹上?
謝謝! PD。 我對Unity2D很陌生
此問題是由兩個碰撞器之間的摩擦引起的,您應該創建一個Physics Material 2D並將其摩擦力設置為0並將其添加到Box Collider 2D材料中。
還應考慮使用Circle Collider而不是障礙物(樹)上的盒子,因為它是圓形的。
您遇到的問題可能是由於gameObjects的邊框仍然相交造成的。 解決此問題的一種方法是將裝配體的大小設置為(0.9,0.9),而不是(1,1),但是隨后您需要添加一個附加腳本來檢查是否可以在不運行對象的情況下進行移動。
由於您有一個基於圖塊的游戲(我猜就像在口袋妖怪中一樣),這應該是一個很好的方法。 如果您對統一引擎不那么了解,則應該在其網站上查看初學者教程。 這是Roguelike教程的鏈接,其中包含您可能想要的完全相同的動作。 一切都解釋得很好,您可以在教程中復制所有腳本的編寫內容;)只是看一下,也許您會發現未知的新事物。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.