目录
一、地图搭建
二、创建角色
前言
开始学习制作一款移动端2d游戏
一、地图搭建
使用Sprite Editor将地图切割为瓦片,在Hierarchy点击加号2D Object创建Tilemap,上方window—>2D—>Tile Palette打开调色盘,添加Tilemap内容,可以点击Edit后通过上方工具栏对内容进行调整。
随意搭建场景
ex1.使用2D Tilemap-Extras插件(https://github.com/Unity-Technologies/2d-extras)
新建Rule map Ground,并添加资源图片根据上下关系设置为这样。
ex2.使用sortingLayer来使图层分开渲染,分级在上面的layer会被下面的覆盖
为Platform添加Tilemap collider 2D,为了防止瓦片之间连接不平整导致任务会卡住在地图的某个位置,再添加一个Composite Collider 2D就可以是整个地图成为整体的碰撞体,这个组件会自动添加Rigidbody 2D,记得设置Body Type为Static。
然后添加一些互动性的元素,放入圆筒酒瓶等并添加Rigidbody2D和Polygon Collider2D,设置相关mass等。
二、创建角色
导入角色并添加刚体和碰撞体后开始写脚本,首先实现左右的移动以及跳跃。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControl : MonoBehaviour
{
private Rigidbody2D rb;
[Header("移动")]
public float speed;
[Header("跳跃")]
public float jumpforce;
[Header("状态检测")]
public bool isGround;
public bool CanJump;
[Header("地面检测")]
public Transform groundCheck;
public float checkRadius;
public LayerMask groundLayer;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
CheckInput();
}
void FixedUpdate()//物理引擎
{
PhysicsCheck();
Movement();
Jump();
}
void CheckInput()//便于检测更多按键
{
if(Input.GetButtonDown("Jump")&& isGround)
{
CanJump = true;
}
}
void Movement()//移动
{
float HorizontalInput = Input.GetAxisRaw("Horizontal");//查询水平轴的当前值并将其存储在变量中(-1~1不包括小数,速度不会逐渐提高)
//逐渐提高使用GetAxis()
rb.velocity = new Vector2(HorizontalInput * speed, rb.velocity.y);
if(HorizontalInput!=0)//转头
{
transform.localScale = new Vector3(HorizontalInput, 1, 1);
}
}
void Jump()//跳跃
{
if(CanJump)
{
rb.velocity = new Vector2(rb.velocity.x, jumpforce);
rb.gravityScale = 4;
CanJump = false;
}
}
void PhysicsCheck()
{
isGround = Physics2D.OverlapCircle(groundCheck.position, checkRadius, groundLayer);
if (isGround)
rb.gravityScale = 1;
}
public void OnDrawGizmos()//绘制检测范围,作为自带函数不需要被调用
{
Gizmos.DrawSphere(groundCheck.position, checkRadius);
}
}