using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public GameObject particle;
public GameObject stoneHit;
public Transform tf;
public Transform e2;
public Material newMaterial; // 新材质
private Material oldMaterial; // 旧材质
private Renderer rd; // 渲染器组件
public Vector3 oldPosition; // 初始位置
void Start()
{
tf = this.transform;
oldPosition = tf.position;
particle = tf.Find("Stone slash").gameObject;
stoneHit = tf.Find("Stones hit").gameObject;
// 获取游戏对象的 Renderer 组件
rd = e2.GetComponent<Renderer>();
// 保存旧材质
oldMaterial = rd.material;
}
public float coolTime;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.W)) {
tf.position += Vector3.forward;
}
if (Input.GetKeyDown(KeyCode.S)) {
tf.position -= Vector3.forward;
}
if (Input.GetKeyDown(KeyCode.A)) {
tf.position += Vector3.left;
}
if (Input.GetKeyDown(KeyCode.D)) {
tf.position -= Vector3.left;
}
if (Input.GetKeyDown(KeyCode.P)) {
doIt = 1;
}
if (Input.GetKeyDown(KeyCode.K)) {
particle.SetActive(false);
}
}
int doIt = 0; // 执行操作中
void FixedUpdate() {
Debug.DrawLine(tf.position, e2.position);//画出射线
if (coolTime > 0) {
coolTime -= Time.deltaTime;
}
if (coolTime < 0.1){ // 预估播放时间为:0.5s
particle.SetActive(false);
stoneHit.SetActive(false);
rd.material = oldMaterial;
}
AutoMoveAndHit();
}
// 射线碰撞的目标对象
RaycastHit hitInfo;
// 射线的最大长度
float maxDistance = 100;
void hit() {
coolTime = 0.5f;
// 创建射线,返回是否检测到碰撞对象
bool raycast = Physics.Raycast(tf.position, e2.position, out hitInfo, maxDistance);
Debug.Log("是否碰撞" + raycast);
stoneHit.transform.position = e2.position;
particle.SetActive(true);
stoneHit.SetActive(true);
rd.material = newMaterial;
// 如果发生碰撞,碰撞信息就被存储到 hitInfo 中
if (raycast)
{
// 获取碰撞点坐标
Vector3 point = hitInfo.point;
Debug.Log("碰撞点坐标:" + point);
// 获取碰撞目标的名称
string name = hitInfo.collider.name;
Debug.Log("碰撞对象名称:" + name);
// 获取目标的碰撞体组件
Collider coll = hitInfo.collider;
//获取目标的Transgorm组件
Transform trans = hitInfo.transform;
}
}
public float speed = 5;
void AutoMoveAndHit() {
if (doIt == 0) {
return;
}
// 计算距离, 逐帧移动
if (doIt == 1) {
// 注视旋转
tf.rotation = Quaternion.LookRotation(e2.position - tf.position);
float distance = Vector3.Distance(tf.position, e2.position);
if (distance > 2) {
tf.position = Vector3.MoveTowards(tf.position, e2.position, speed*Time.deltaTime);
return;
}
doIt = 2;
}
// 移动已到位,执行攻击
if (doIt == 2) {
doIt =3;
hit();
}
// 攻击结束,退回原位置
if (doIt == 3) {
if (coolTime > 0.1) { // 等待攻击动画完成
return;
}
// 注视旋转
tf.rotation = Quaternion.LookRotation(oldPosition -tf.position);
float distance = Vector3.Distance(tf.position, oldPosition);
Debug.Log("当前位置distance:" + distance);
if (distance > 0) {
tf.position = Vector3.MoveTowards(tf.position, oldPosition, speed*Time.deltaTime);
} else {
doIt = 0;
}
}
}
}
Unity回合攻击
于 2023-09-28 14:37:02 首次发布