用unity制作一個寶可夢——1.入門和瓦片地圖

1.下載unity社區(qū)以及對應(yīng)的unity版本(我用的是2020.3.46f1c1,最好用2020.3.48f1c1,是長期支持版)
2.創(chuàng)建2D核心模板,取消勾選版本控制(不要用unity默認(rèn)的版本控制,會打不開項目)
3.下載圖片資源到本地,解壓資源(最好留個備份,不要和寶可夢項目放在一起)

4.在unity編輯器中創(chuàng)建一個Art的文件夾用來存放游戲的藝術(shù)資源,將解壓出來的資源文件放入Art中并設(shè)置好像素單元為16*16
5.創(chuàng)建玩家物體,以及畫背景(注意創(chuàng)建文件夾的路徑,別搞亂,否則后續(xù)容易找不到)
6.創(chuàng)建兩個排序圖層Sorting Layer,分別是Player和BackGround,注意調(diào)整順序!分別給玩家和背景的物體選擇排序圖層
7.創(chuàng)建PlayerController腳本,掛載到玩家上
8.編寫腳本,發(fā)現(xiàn)移動有問題,改了下代碼
//控制玩家的腳本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed; //玩家的移動速度
private static bool isMoving; //是否處在移動
private void Update()
{
if (!isMoving)
{
var input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (input != Vector2.zero) //如果輸入的值不為0
{
var targetPos = transform.position; //targetPos:目標(biāo)位置 transform.position:當(dāng)前位置
targetPos.x += input.x; //x方向加上垂直方向輸入進來的值
targetPos.y += input.y; //y方向加上水平方向輸入進來的值
StartCoroutine(Move(targetPos, input));
}
}
}
IEnumerator Move(Vector3 targetPos, Vector2 input)
{
isMoving = true;
// 循環(huán)判斷當(dāng)前位置與目標(biāo)位置之間的距離是否大于一個很小的數(shù)值
while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
// 計算每幀應(yīng)該移動的距離,并讓物體朝目標(biāo)位置移動一步
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
// 讓協(xié)程函數(shù)在每個FixedUpdate()中等待一次,確保物理計算與 Update() 同步進行
yield return new WaitForFixedUpdate();
}
// 直接將物體移動到精確定位到目標(biāo)位置上,避免偏差堆積
transform.position = targetPos;
isMoving = false;
}
}