当前位置:网站首页>Unity3d RPG implementation (medium)
Unity3d RPG implementation (medium)
2022-07-03 03:11:00 【Sunny summer.】
Set the basic attributes and status of the enemy
download rpg monster Package and import , Then we need to update the material . And write the code .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public enum EnemyStates { GUARD,PATROL,CHASE,DEAD}
[RequireComponent(typeof(NavMeshAgent))]
public class EnemyController : MonoBehaviour
{
public EnemyStates enemyStates;
private NavMeshAgent agent;
// Start is called before the first frame update
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
SwitchState();
}
void SwitchState()// Realize a simple state switch
{
switch (enemyStates)
{
case EnemyStates.GUARD:
break;
case EnemyStates.PATROL:
break;
case EnemyStates.CHASE:
break;
case EnemyStates.DEAD:
break;
}
}
}

add to tag and layer.
It is necessary to realize occlusion elimination for the enemy , So in pipeline Except player More than a enemy that will do .
Attack the enemy
Set another click event :
![]()

stay playerController Register the function in :

MoveToEnemy Functions like this can be used alt+enter fill

have access to alt+enter Realization
Add attack animation to players , Note that the switch from attack to running must be exit time Set to 1, Only in this way can the animation be played .

StopAllCoroutines();// So that the character can also click to go to other places in the process of moving towards the goal , Interrupt operation
agent.isStopped = false;// Add this sentence , It solves the problem that characters cannot act once they attack
Later on playercontroller Code to move towards the enemy after the attack :
void EventAttack(GameObject target)
{
if (target != null)
{
attackTarget = target;
StartCoroutine(MoveToAttackTarget());
}
}
IEnumerator MoveToAttackTarget()
{
// In order to prevent the next time after this click agent Unable to act , Use recovery at the beginning of this click
agent.isStopped = false;
transform.LookAt(attackTarget.transform);
while (Vector3.Distance(transform.position, attackTarget.transform.position) > 1)
{
agent.destination = attackTarget.transform.position;
yield return null;
}
// When arriving at the designated place , command agent stop it
agent.isStopped = true;
// The attack has cd Time
if (lastAttackTime < 0)
{
animator.SetTrigger("Attack");
lastAttackTime = 0.5f;
}
}
}The way to go to the enemy is through coordination , Join in lastAttackTime Used to attack cd The cooling of .
Because the navigation system comes with destination It's going to keep moving , So we need to realize when the distance is 1 When you stop moving, use agent
isStopped by true To execute . Corresponding , The initial needs of this process are set isStop by false.
bug:
After executing the above code, you will find , Once the character attacks the enemy, he can no longer move by clicking on the ground , This is because isStopped Set up in order to false, So you need to click on the ground to move
effect :
( The mouse pointer cannot be displayed )
here MouseManger
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using System;
//[System.Serializable]
//public class EventVector3 : UnityEvent<Vector3> { }// Declare an event
public class MouseManager : MonoBehaviour
{
//public EventVector3 OnMouseClicked;
public event Action<Vector3> OnMouseClicked;
public event Action<GameObject> OnEnemyClicked;
RaycastHit hitInfo;
public static MouseManager Instance;
public Texture2D point, doorway, attack, target, arrow;
private void Awake()
{
if (Instance != null) Destroy(gameObject);
Instance = this;
}
private void Update()
{
SetCursorTexture();
MouseControl();
}
void SetCursorTexture()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);// Get rays
// Output the ray information to hitInfo
if (Physics.Raycast(ray, out hitInfo)) {
switch (hitInfo.collider.gameObject.tag)
{
case "Ground":
Cursor.SetCursor(target, new Vector2(16,16), CursorMode.Auto);
break;
case "Enemy":
Cursor.SetCursor(attack, new Vector2(16, 16), CursorMode.Auto);
break;
}
}
}
void MouseControl()
{
if (Input.GetMouseButtonDown(0) && hitInfo.collider != null)
{
if (hitInfo.collider.CompareTag("Ground"))
{
OnMouseClicked?.Invoke(hitInfo.point);
// Click to send the location to OnMouseClicked This event registers the function and calls
}
if (hitInfo.collider.CompareTag("Enemy"))
{
OnEnemyClicked?.Invoke(hitInfo.collider.gameObject);
// Click to send the location to OnMouseClicked This event registers the function and calls
}
}
}
}
Time setting isStopped by true.

And then there's another one bug, Cannot move when entering the state of attacking the enemy , You can only move after the attack , Add here :

Then you can attack the enemy :
Camera's Freelook
First the cvm Turn off the , Enable cinemachine Medium freelook

Drag the character in , At this point, you can see three red circles

There are three circles , It means that the camera can rotate freely in these three dimensions :


Running the game can realize the perspective switching of the scene .
We will y The movement of the axis is realized with the mouse wheel ( This name comes from setting Inside input manager Name setting in )


Change the size of three circles
The actual use effect of the three circles is as follows :

If you want to keep the value in the modification :

If you want the camera to follow the direction of the person when the person moves, you can modify bindingmode:
Here is a small detail , Add some TODO: FIXME: As a to-do

The pursuit of the enemy
Add code to detect players for enemies :
bool FoundPlayer()
{
var colliders = Physics.OverlapSphere(transform.position, sightRadius);
foreach(var target in colliders)
{
if (target.CompareTag("Player"))
{
return true;
}
}
return false;
}Call when switching state :

Don't forget to add collision bodies to players
add , We are here for hierarchy Medium player and enemy It's been modified , Want these changes to cover project The inside can be used override.

Next, we'll implement chase, Before writing, you can record what you want to do in this way , Convenient sorting logic .
边栏推荐
- 基于QT的tensorRT加速的yolov5
- MySql实战45讲【索引】
- L'index des paramètres d'erreur est sorti de la plage pour les requêtes floues (1 > Nombre de paramètres, qui est 0)
- el-tree搜索方法使用
- I2C subsystem (III): I2C driver
- TCP 三次握手和四次挥手机制,TCP为什么要三次握手和四次挥手,TCP 连接建立失败处理机制
- Serious security vulnerabilities reported by moxa mxview network management software
- MySql实战45讲【SQL查询和更新执行流程】
- Practice of traffic recording and playback in vivo
- Vs Code configure virtual environment
猜你喜欢

用docker 连接mysql的过程

Kubernetes cluster log and efk architecture log scheme

Vs Code configure virtual environment

Installation and use of memory leak tool VLD

Gavin teacher's perception of transformer live class - rasa project's actual banking financial BOT Intelligent Business Dialogue robot architecture, process and phenomenon decryption through rasa inte

VS 2019安装及配置opencv

Super easy to use logzero
![[error record] the parameter 'can't have a value of' null 'because of its type, but the im](/img/1c/46d951e2d0193999f35f14d18a2de0.jpg)
[error record] the parameter 'can't have a value of' null 'because of its type, but the im

MySql实战45讲【事务隔离】

TCP 三次握手和四次挥手机制,TCP为什么要三次握手和四次挥手,TCP 连接建立失败处理机制
随机推荐
Segmentation fault occurs during VFORK execution
超好用的日志库 logzero
VS code配置虚拟环境
Add automatic model generation function to hade
Chart. JS multitooltip tag - chart js multiTooltip labels
com.fasterxml.jackson.databind.exc.InvalidFormatException问题
MySQL practice 45 [SQL query and update execution process]
VS 2019 配置tensorRT生成engine
Parameter index out of range (1 > number of parameters, which is 0)
C#通用接口调用
Distributed transaction
MySql实战45讲【全局锁和表锁】
力扣------网格中的最小路径代价
Are there any recommended term life insurance products? I want to buy a term life insurance.
二维数组中的元素求其存储地址
Docker install MySQL
将时间戳转为指定格式的时间
Three. JS local environment setup
Gavin teacher's perception of transformer live class - rasa project's actual banking financial BOT Intelligent Business Dialogue robot architecture, process and phenomenon decryption through rasa inte
The process of connecting MySQL with docker