using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{
public float speed = 5f; //移动速度
private int maxHealth = 5; //最大生命值
private int currentHealth; //当前生命值
public int MyMaxHealth { get { return maxHealth; } }
public int MyCurrentHealth { get { return currentHealth; } }
private float invincibleTime = 2f; //无敌时间2秒
private float invincibleTimer; //无敌计时器
private bool isInvincible; //是否无敌
private Vector2 lookDirection = new Vector2(1, 0); //默认朝向右方
public GameObject bulletPrefab; //获取子弹
public Joystick joystick; //操作杆
public Text xueliang; //血量
Rigidbody2D rbody; //刚体组件
Animator anim; //获取动画组
// Start is called before the first frame update
void Start()
{
currentHealth = 2;
invincibleTimer = 0;
rbody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
//transform.Translate(transform.right * speed * Time.deltaTime);
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical"); //键盘输入
//float moveX = joystick.Horizontal; //操纵杆输入
//float moveY = joystick.Vertical;
//角色方向更具前后左右来选中方向
Vector2 moveVector = new Vector2(moveX, moveY);
if (moveVector.x != 0 || moveVector.y != 0)
{
lookDirection = moveVector;
}
anim.SetFloat("Look X",lookDirection.x);
anim.SetFloat("Look Y",lookDirection.y);
//方向移动动画
anim.SetFloat("Speed",moveVector.magnitude);
//基础移动------------------------------------------------
Vector2 position = rbody.position;
//position.x += moveX * speed * Time.deltaTime;
//position.y += moveY * speed * Time.deltaTime;
position += moveVector * speed * Time.deltaTime;
rbody.MovePosition(position);
//无敌记时---------------------------------------------
if (isInvincible)
{
invincibleTimer -= Time.deltaTime;
if (invincibleTimer < 0)
{
isInvincible = false; //无敌时间结束
}
}
//按下J键,创建发射子弹
if (Input.GetKeyDown(KeyCode.J))
{
anim.SetTrigger("Launch"); //播放发射动画
GameObject bullet = Instantiate(bulletPrefab, rbody.position + Vector2.up * 0.5f,Quaternion.identity);
BulletlconController bc = bullet.GetComponent<BulletlconController>();
if (bc != null)
{
bc.Move(lookDirection, 300);
}
}
}
/// <summary>
/// 改变玩家的生命值
/// </summary>
/// <param name="amount"></param>
public void ChangeHealth(int amount)
{
if (amount < 0) //玩家收到伤害
{
if (isInvincible == true) //玩家收到伤害时是无敌:跳出ChangeHealth
{
return;
}
isInvincible = true; //玩家受到伤害时不是无敌:先改成无敌
invincibleTimer = invincibleTime; //不是无敌:再改设置计时时间再正常走ChangeHealth
}
//把玩家生命值约束在0和max之间
currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
Debug.Log(currentHealth+"/"+maxHealth);
xueliang.text = currentHealth + "/" + maxHealth;
}
}
玩家C#
最新推荐文章于 2023-03-23 14:28:41 发布