我想创建一个游戏,我可以通过磁贴移动播放器。我不知道如何让它跳跃以及如何使它平滑。 到目前为止,这是我的代码:
using UnityEngine;
using System.Collections;
public class PlayerScript : MonoBehaviour {
/*
* TILE BY TILE MOVEMENT
* */
private bool isMoving = false;
private bool isJumping = false;
private Vector3 targetPosition = new Vector3();
private Vector3 prevPosition = new Vector3();
public static bool canMove = true;
private Rigidbody2D rb2D;
void Start(){
prevPosition = transform.position;
rb2D = GetComponent<Rigidbody2D> ();
}
public void Move(string moveDirection){
if (isMoving == false && canMove == true) {
isMoving = true;
switch (moveDirection.ToLower()) {
case "left":
prevPosition = transform.position;
targetPosition = prevPosition + new Vector3(-2,0,0);
targetPosition.x = Mathf.Round(targetPosition.x);
break;
case "right":
prevPosition = transform.position;
targetPosition = prevPosition + new Vector3(2,0,0);
targetPosition.x = Mathf.Round(targetPosition.x);
break;
}
}
}
public void CancelMove(){
targetPosition = prevPosition;
Debug.Log("Canceled move");
}
void Update(){
if (isMoving == false) {
//Checks if there is ground
RaycastHit2D hit;
hit = Physics2D.Raycast (transform.position, -Vector2.up, 1.2f, 1 << LayerMask.NameToLayer("Ground"));
Debug.DrawRay (transform.position, -Vector2.up* 1.2f);
RaycastHit2D hitSideRight;
hitSideRight = Physics2D.Raycast (transform.position, Vector2.right, 1.2f, 1 << LayerMask.NameToLayer("Ground"));
Debug.DrawRay (transform.position, Vector2.right* 1.2f);
RaycastHit2D hitSideLeft;
hitSideLeft = Physics2D.Raycast (transform.position, -Vector2.right, 1.2f, 1 << LayerMask.NameToLayer("Ground"));
Debug.DrawRay (transform.position, -Vector2.right* 1.2f);
if((hitSideLeft.collider != null && hitSideLeft.collider.tag != "Box") || (hitSideRight.collider != null && hitSideRight.collider.tag != "Box")){
CancelMove();
Debug.Log("Can't move");
}
if (hit.collider != null || hit.collider == null){
if (Input.GetAxisRaw ("Horizontal") > 0 && hitSideRight.collider == null) {
Move ("right");
}
if (Input.GetAxisRaw ("Horizontal") < 0 && hitSideLeft.collider == null) {
Move ("left");
}
if(Input.GetKeyDown(KeyCode.Space)){
rb2D.AddForce(new Vector2(0,800));
}
}
} else {
if( transform.position.x != targetPosition.x )
{
// Move this object towards the target position
transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * 5f);
}
else
{
isMoving = false;
}
}
}
}
此脚本已附加到播放器。玩家有一个rigidbody2D和一个boxCollider2D:http://i.stack.imgur.com/sEV5b.jpg