Unity project imitates cs knowledge points

1. Introduction
1. Character part
a, character movement
b, camera rotation
c, player shooting: animation, audio, enumeration, bullet hole, magnification
2, enemy part
a, enemy clone
b, walking towards the player: distance, direction, Orientation, dot product, cross product

2. Character part
(1), character movement

 CharacterController c;//角色控制器
    Vector3 moveDirection = Vector3.zero;//移动方向
    float moveSpeed = 6, jumpSpeed = 4;
    float gravity = 20;
    void Start()
    {
    
    
        c = GetComponent<CharacterController>();
    }
    void Update()
    {
    
    
        if (c.isGrounded)
        {
    
    
            float h = Input.GetAxis("Horizontal");
            float v = Input.GetAxis("Vertical");
            //固定坐标的前后左右移动
            //direction = new Vector3(h, 0, v);
            //第一人称移动,normalized表示长度1
            moveDirection = (transform.right * h + transform.forward * v).normalized;
            if (Input.GetButton("Jump"))
            {
    
    
                moveDirection.y = jumpSpeed;
            }
        }
        //一直有一个重力加速度
        moveDirection.y -= gravity * Time.deltaTime;
        c.Move(moveDirection * moveSpeed * Time.deltaTime);
    }

Talk about Move and SimpleMove
1. SimpleMove
SimpleMove can only move on the plane, without Y-axis movement.
Movement has its own speed. Therefore, there is no need to multiply Time.deltaTime
when moving with its own gravity.
2.
There is no limit to the moving direction of Move
. When moving, you need to multiply Time.deltaTime
and you need to do gravity yourself.

It is not enough to have only the first-person movement code in (1), and the direction of the character needs to be controlled by the mouse to reflect the first-person movement.

(2), camera rotation (the character faces the direction, the script hangs on the character)

Vector3 cameraRotate;
	float rotateSpeed = 3f;
	void Update () {
    
    
		//获取鼠标水平和竖直方向的偏移量
		float x = Input.GetAxis("Mouse X");
		float y = Input.GetAxis("Mouse Y");
		//左右旋转(绕Y轴旋转);
		cameraRotate.x -= y * rotateSpeed;
		//抬头低头(绕X轴旋转)
		cameraRotate.y += x * rotateSpeed;
		//抬头低头范围
		cameraRotate.x = Mathf.Clamp(cameraRotate.x, -45, 45);
		//左右旋转范围(CS人物是可以左右无限制旋转的,所以这里可以去掉)
		//cameraRotate.y = Mathf.Clamp(cameraRotate.x,-90,90);
		transform.rotation = Quaternion.Euler(cameraRotate.x, cameraRotate.y, 0);
	}

For better movement, you can try to hide the mouse

Cursor.lockState = CursorLockMode.Locked;

(3), the player shoots

 Transform pos;//枪口位置
    private GameObject explosionFx;//爆炸特效
    private AudioClip explosionAudios, fireAudios;//爆炸音频,开枪音频
    void Start()
    {
    
    
        //动态加载资源(路径: Assets/Resources/Prefabs/HitBlood)
        explosionFx = Resources.Load<GameObject>("Prefabs/HitBlood");
        explosionAudios = Resources.Load<AudioClip>("Audios/boom");
        fireAudios = Resources.Load<AudioClip>("Audios/shoot");
    }
    void Update()
    {
    
    
        if (Input.GetButtonDown("Fire1"))
        {
    
    
            //点击左键,枪口位置发出开枪音频(自动消失)音量1
            AudioSource.PlayClipAtPoint(fireAudios, pos.position, 1f);
            RaycastHit hit;//碰撞信息
            //检测射线(枪口位置,人物向前方向,碰撞信息,距离20米)
            if (Physics.Raycast(pos.position, transform.forward, out hit, 20))
            {
    
    
                GameObject go = Instantiate(explosionFx, hit.point, Quaternion.identity);
                Destroy(go, 1f);
                //播放爆炸特效(自动消失),音量1
                AudioSource.PlayClipAtPoint(explosionAudios, hit.point, 1f);
                Destroy(hit.collider.gameObject);
            }
        }
    }

Note:
(a), cs should be fired with rays, because of the need to realize the magnification (I can't use the front sight to align), I finally chose to launch with the center of the camera instead of the muzzle (b), when shooting, you need to have a
insert image description here
shot animation
insert image description here

//方法:
Animation an;//动画
void Start()
{
    
    
  an.GetComponent<Animation>();
}
//an.play("动画名");
an.play("Fire2");

©, Audio

public class ResManage
{
    
    
    //该类的目的是为了存储字符串,简洁其他类
    //声音路径
    public const string walk = "Sounds/playWalk";//走路声音
    public const string run = "Sounds/playRun";//跑步声音
}
 AudioClip landClip, runClip;//音频片段
 AudioSource audios;//音频组件
 void Start()
 {
    
    
  //音频资源
   audios = GetComponent<AudioSource>();
   //动态加载资源,(体现ResManage类的目的)
   landClip = Resources.Load<AudioClip>(ResManage.walk);
   runClip = Resources.Load<AudioClip>(ResManage.run);
 } 

insert image description here
(d) Application of enumeration
When playing animation, it is usually written in enumeration (write the animation of the enemy here)
insert image description here

insert image description here

 enum States
    {
    
    
        Idle,
        Run,
        Death,
        Attack
    };
    void GetStates(States s)
    {
    
    
        switch (s)
        {
    
    
            case States.Idle:
                an.Play(ResManage.nurseIdle);
                break;
            case States.Run:
                an.Play(ResManage.nurseRun);
                break;
            case States.Death:
                an.Play(ResManage.nurseDeath);
                break;
            case States.Attack:
                an.Play(ResManage.nurseAttack);
                break;
            default:
                break;
        }
    }

Usage: GetStates(States.Idle);
(e), bullet hole position

if (Physics.Raycast(ray, out hit, 100))//摄像机发射
 {
    
    
  if (hit.collider.CompareTag("Plane"))
   {
    
    
    //子弹打洞
    //打到地板克隆弹孔
    GameObject go = Instantiate(holeEffect, hit.point, holeEffect.transform.rotation);
    //让弹孔与射线碰撞体的法线垂直(让弹孔总是贴在碰撞体表面)
    go.transform.LookAt(hit.point - hit.normal);
    //让弹孔与碰撞体表面保持0.03距离(这里看着合适就行)
    go.transform.Translate(Vector3.back * 0.03f);
    Destroy(go, 1f);
   }
  }

(f), magnification (subtraction means magnification)
camera.GetComponent().fieldOfView-=45;
3. Enemy part
(1), clone enemy
(with a certain point (x1, y1, z1) as the center range 1~5 m spawns 5 enemies)

for (int i = 0; i < 5; i++)
  {
    
    
    float a = Random.Range(1, 5);
    //从原点坐标获取任意一个方向的向量
    Vector2 b = Random.insideUnitCircle;
    //获取向量的单位向量
    Vector2 c = b.normalized;
    //得到位置
    Vector3 d = new Vector3(x1 + c.x * a, y1, z1 + c.y * a);
    Instantiate(enemy, d, transform.rotation);
  }


(2) The distance between the enemy and the player :
Use Vector.Distance (enemy position, player position); judge the distance and then play the animation to approach the player.

if (Vector3.Distance(transform.position, player.transform.position) <= 10)

Orientation question:

//敌人指向玩家方向
dir = (player.transform.position - transform.position).normalized;

Towards the question:

transform.LookAt(player.transform.position);

(3), determine the enemy's position
a, point multiplication
insert image description here

//点乘
float a = Vector3.Dot(transform.forward, enemy.transform.position - player.transform.position);
if (a <= 0)
 {
    
    
  tipWarn.text = "警告:后方发现敌人";
 }
else
 {
    
    
   tipWarn.text = "警告:前方发现敌人";
 }

b. Cross product
insert image description here

Guess you like

Origin blog.csdn.net/weixin_44706943/article/details/127181588