目錄
一、地圖搭建
二、建立角色
前言
開始學習制作一款移動端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);
}
}