點選asset store可以從裡面下載免費資源來使用,在練習製作遊戲時會有很大的幫助
也可以直接上網查詢Unity asset store來下載
https://assetstore.unity.com/zh
先在Hierarchy欄位中建立一個2D Object裡的square方塊當作角色
點選方塊在Inspector中加入rigidbody2D和box collider2D
待更
結合移動和碰撞的基礎功能
程式碼
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
[RequireComponent(typeof(Rigidbody2D))]
public class playcontrol : MonoBehaviour
{
Rigidbody2D rigid2D;
[SerializeField]
private float speed;
[SerializeField]
private float speed_x_constraint;
public int hp = 20;
public int jumpcheck=0;
void Start()
{
rigid2D = this.gameObject.GetComponent<Rigidbody2D>();
}
void Update()
{
float deltatime = Time.deltaTime;
//跳躍
if (Input.GetKeyDown(KeyCode.Space) && jumpcheck<2)
{
rigid2D.AddForce(new Vector2(0, 200), ForceMode2D.Impulse);
jumpcheck +=1;
}
//右移動
if (Input.GetKey(KeyCode.D))
{
rigid2D.velocity = new Vector2(speed_x_constraint, rigid2D.velocity.y);
}
//左移動
if(Input.GetKey(KeyCode.A))
{
rigid2D.velocity = new Vector2(-speed_x_constraint, rigid2D.velocity.y);
}
}
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "trap") {
hp -= 1;
rigid2D.AddForce(new Vector2(0, 100), ForceMode2D.Impulse);
}
if (coll.gameObject.tag == "Scenesobject") {
jumpcheck = 0;
}
}
}
晚點整理完上圖
參考資料
https://www.youtube.com/watch?v=_LdnD8zN5OU