[英]Unity 2D: Why does my character move through other geometry without stopping?
每當使用A或D時,其他游戲對象都不會停止我的角色(二維游戲對象)。 角色具有附加的角色控制器組件以及具有3種動畫(空閑,行走和着陸)的動畫控制器。
//Variables
public float speed = 10F;
public float jumpSpeed = 15F;
public float gravity = 20F;
public float airSpeed = 5F;
public Vector2 moveDirectionResultant = Vector2.zero;
private CharacterController controller;
private Animator animator;
void Start() {
controller = GetComponent<CharacterController>();
animator = GetComponent<Animator>();
}
void Update() {
animator.SetFloat ("AirSpeed", moveDirectionResultant.y);
if (controller.isGrounded)
{
animator.SetBool("Grounded", true);
animator.SetBool("Move", false);
if (Input.GetKeyDown (KeyCode.W))
{
moveDirectionResultant.y = jumpSpeed;
}
else
{
moveDirectionResultant.y = 0;
}
if (Input.GetKey (KeyCode.D))
{
transform.Translate(speed * Time.deltaTime, 0f, 0f);
animator.SetBool("Move", true);
}
if (Input.GetKey (KeyCode.A))
{
transform.Translate(-speed * Time.deltaTime, 0f, 0f);
animator.SetBool("Move", true);
}
}
else
{
animator.SetBool("Grounded", false);
animator.SetBool("Move", false);
if (Input.GetKey (KeyCode.D))
{
transform.Translate(airSpeed * Time.deltaTime, 0f, 0f);;
}
if (Input.GetKey (KeyCode.A))
{
transform.Translate(-airSpeed * Time.deltaTime, 0f, 0f);;
}
}
//Applying gravity to the controller
moveDirectionResultant.y -= gravity * Time.deltaTime;
//Making the character move
controller.Move(moveDirectionResultant * Time.deltaTime);
}
}
我對編碼還比較陌生,因此,如果解決方案顯而易見,對不起!
嘗試將RigidBody2D
和BoxCollider2D
到您的游戲對象以及想要與之碰撞的任何游戲對象。 如果您希望發生碰撞導致事件發生(稱為方法),請使用附加在游戲對象上的腳本中的OnCollisionEnter2D(Collision2D collision)
方法。 來自unity網站的本教程視頻詳細介紹了2D角色控制和動畫: http : //unity3d.com/learn/tutorials/modules/beginner/2d/2d-controllers
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.