实现2D主角移动,跳跃和转头函数
public bool facingRight=true;
public float movespeed;
public float moveForce = 365f;
public float maxSpeed = 5f;
public float jumpForce = 1000f;
private Transform groundCheck;
private bool grounded = false;
private Animator anim;
public bool jump = false;
void Flip()
{
facingRight=!facingRight;
Vector3 theScale=transform.localScale;
theScale.x*=-1;
transform.localScale=theScale;
}
void Start () {
anim = GetComponent<Animator>();
}
void Update () {
if (Input.GetButtonDown("Jump"))
jump = true;
GetComponent<Rigidbody2D>().
constraints = RigidbodyConstraints2D.FreezeRotation;
}
void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");
anim.SetFloat("Speed", Mathf.Abs(h));
Rigidbody2D rb = GetComponent<Rigidbody2D>();
if (h * rb.velocity.x < maxSpeed)
rb.AddForce(Vector2.right * h * moveForce);
if (Mathf.Abs(rb.velocity.x) > maxSpeed)
rb.velocity = new Vector2(Mathf.Sign(rb.velocity.x) * maxSpeed, rb.velocity.y);
if (h > 0 && !facingRight) Flip();
else if (h < 0 && facingRight) Flip();
if(jump)
{
anim.SetTrigger("Jump");
rb.AddForce(new Vector2(0, jumpForce));
jump = false;
}
}
}
使用TileMap快速搭建2D游戏场景
首先在场景创建TileMap
接着打开Talpaletter
然后把要绘制的场景,整个拖进。点击画笔就可以在scene绘制
给场景赋予碰撞体的话需要在给Grid的Tilemap添加Tilemap collider2D和rigidbody 2D组件,然后为了让地面不受重力掉下去或者被它上表面的物体压下去,将rigidbody 2D设为静态(static)刚体
//此功能是转载别人的,侵删
Rigidbody2D锁定对象旋转,使其装上碰撞器时不会随意翻转角度
GetComponent().constraints = RigidbodyConstraints2D.FreezeRotation;
实现摄像机跟随player
把以下代码挂在主相机
public GameObject player;
public float speed;
public float minPos;
public float maxPos;
void Start()
{
}
void Update()
{
FixCameraPos();
}
void FixCameraPos()
{
float pPoX=player.transform.position.x;
float cPoX=transform.position.x;
if(pPoX-cPoX>3)
{
transform.positon=new Vector3(cPoX+speed*Time.deltaTime,transform.position.y,transform.position.z);
}if(pPoX-cPoX<-3)
{
transform.position=new Vector3(cPoX-speed*Time.deltaTime,transform.position.y,transform.position.z);
}
float realPosX=Mathf.Clamp(transform.position.x,minPosx,maxPox);//限制摄像机移动
transform.position=new Vector3(realPosX,transform.position.y,transform.position.z);
}