Step8:设置掉血区域
设置掉血区域
与设置触发器的原理类似
首先更改作用点,移动到 X:0.5 Y:0
然后调整Sprite Sort:Pivot
然后增加Collision Box 2D
勾选 Is Triggered
public int damageNum=-1;
void OnTriggerStay2D(Collider2D other)
{
RubyController rubyController = other.GetComponent<RubyController>();
if(rubyController != null)
{
rubyController.ChangeHealth(damageNum);
}
}
Step9:设置无敌时间
//设置玩家无敌的时间间隔
public float timeInvincible = 2.0f;
这是一个恒定的常量
//设置是否无敌的变量
bool isInvincible;
用于判断是否无敌
//定义变量
float invincibleTimer;
这个用于无敌时间的计时
void Update()
{
......
//判断是否处于无敌的状态,进入倒计时
if (isInvincible)
{
//每次减去一帧消耗的时间
invincibleTimer -= Time.deltaTime;
if (invincibleTimer < 0)
{
//取消无敌状态
isInvincible = false;
}
}
}
public void ChangeHealth(int amount)
{
if (amount < 0){
if (isInvincible){
return;
}
//重置计时器
isInvincible = true;
invincibleTimer = timeInvincible;
}
.....
}
Step10:平铺掉血区域
调整 drawMode:Tiled
其次调整 Mesh Type:Full Rect
Step11:准备敌人,设定敌人的移动方式,设定动画
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
// Start is called before the first frame update
Rigidbody2D r2d;
Vector2 position;
public float speed;
public float ChangeTime = 3f;
public float timer = 3f;
int direction = 1;
public bool vertical = true;
Animator animator;
void Start()
{
r2d = GetComponent<Rigidbody2D>();
position = r2d.position;
timer = ChangeTime;
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
speed = 1.0f;
timer -= Time.deltaTime;
if (timer < 0)
{
direction = -direction;
timer = ChangeTime;
}
}
void FixedUpdate()
{
if (vertical)
{
position.y += Time.deltaTime * speed * direction;
animator.SetFloat("MoveX", 0);
animator.SetFloat("MoveY", direction);
}
else
{
position.x += Time.deltaTime * speed * direction;
animator.SetFloat("MoveX", direction);
animator.SetFloat("MoveY", 0);
}
r2d.MovePosition(position);
}
void OnCollisionEnter2D(Collision2D other)
{
RubyController player = other.gameObject.GetComponent<RubyController>();
if (player != null)
{
player.ChangeHealth(-1);
}
}
}
Step12:用已知动画片段设计人物行走
首先增加Animator组件,保存至一个文件夹
然后点击它,选择open
然后删除所有树,新建混合树
删除现有的那一个初始的
选择 parameters,新建MoveX,MoveY
然后 点击混合树选择Blend type,新建parameters
增加Motions,然后填充动画剪辑,最后加入代码控制
Animator animator;
void Start()
{
rigidbody2D = GetComponent<Rigidbody2D>();
timer = changeTime;
animator = GetComponent<Animator>();
}
animator.SetFloat("MoveX", 0);s
animator.SetFloat("MoveY", direction);
animator.SetFloat("Move X", direction);
animator.SetFloat("Move Y", 0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%