图形基础"/>
图形基础
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public Vector3 point;
public Transform A;
public Transform B;
public Transform C;
//正弦是sin,余弦是cos.是相对直角三角形来说的,正弦是一个角的对边比斜边,余弦是一个角的临边比斜边。
//a向量*b向量 = |a|*|b|*cos@
//当A向量与B向量的夹角为0度时 点乘的值为1;
//当A B 夹角为90/-90度时,值为0;
//当A B夹角为180/-180 度时,值为-1;
float Dot(Vector3 a, Vector3 b) {
return a.x * b.x + a.y* b.y + a.z * b.z;
}
float SqrMagnitude(Vector3 v3) {
float all = v3.x * v3.x + v3.y * v3.y + v3.z * v3.z; //Mathf.Pow
return Mathf.Sqrt(all);
}
// Update is called once per frame
void Update()
{
Debug.Log(A.forward);
Debug.Log("长度"+SqrMagnitude(A.position) +"api:"+ A.position.magnitude);
Debug.DrawLine(Vector3.zero, A.position, Color.red);
Debug.DrawLine(Vector3.zero, B.position, Color.blue);
Debug.Log("点乘:" + Dot(A.position, B.position) +"api:"+Vector3.Dot(A.position, B.position));
Debug.DrawLine(Vector3.zero,A.position.normalized , Color.yellow); //归一化
Debug.Log("夹角:" + Vector3.Angle(A.position, B.position) +":"+ Dot(A.position, B.position) /(A.position.magnitude * B.position.magnitude));
CheckFire(A.position, B.position);
}
//可判断物体之间的夹角,在做攻击范围检测时使用,例如:玩家向前劈砍动作,而劈砍的范围为-45度到45度,长度为2,如图所示:
void CheckFire(Vector3 a, Vector3 b) {
//首先判断距离是否小于攻击距离2,然后判断角度:
//if (Vector3.Distance(a, b) < 2) return;
//使用 点乘进行角度判断(B.position - A.position)作用 是 B的左边转化为相对A。 默认是相对原点
float cosValue = Vector3.Dot(A.forward.normalized, (B.position - A.position).normalized);
//Mathf.Acos 返回 f 的反余弦 - 其余弦为 f 的角度(以弧度为单位)。
//Mathf.Rad2Deg弧度到度换算常量 == 360 / (PI * 2)
Debug.Log(Mathf.Acos(cosValue) * Mathf.Rad2Deg + " "+ cosValue);
//如果大于0说明敌人在自身前面
// 如果小于0说明敌人在自身后面
// 如果等于0说明敌人在自身左右
}
}
//void Run()
//{
// //点哪去哪
// if (Input.GetMouseButtonDown(0))
// {
// Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// RaycastHit hit;
// if (Physics.Raycast(ray, out hit))
// {
// if (hit.collider.gameObject.name.Equals("ditu"))
// {
// target = hit.point;
// }
// }
// }
// //移动
// A.transform.position = Vector3.Lerp(A.transform.position, target, Time.deltaTime * 10);
// B.transform.position = Vector3.Lerp(B.transform.position, A.transform.position, Time.deltaTime*0.5f);
// XuanZhuan();
//}
//void XuanZhuan() {
// Vector3 relativePosition = A.position - B.position; //目标点减去起始点(要作用的点)。
// Vector3 result = Vector3.Cross(B.forward, relativePosition); //
// //叉乘结果判断从哪个方向旋转
// Vector3 axis;
// if (result.y > 0)
// {
// axis = Vector3.up;
// }
// else {
// axis = Vector3.down;
// }
// float current = Vector3.Angle(B.forward, A.position - B.position);
// if (current > 5 || current < -5)
// {
// B.Rotate(axis, current*Time.deltaTime *10,Space.World);
// }
//}
更多推荐
图形基础
发布评论