当前位置:网站首页>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 .
边栏推荐
- C语言初阶-指针详解-庖丁解牛篇
- Process the dataset and use labelencoder to convert all IDs to start from 0
- [C language] MD5 encryption for account password
- How to implement append in tensor
- Update and return document in mongodb - update and return document in mongodb
- 基于Qt的yolov5工程
- 处理数据集,使用LabelEncoder将所有id转换为从0开始
- From C to capable -- use the pointer as a function parameter to find out whether the string is a palindrome character
- C language beginner level - pointer explanation - paoding jieniu chapter
- 别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!
猜你喜欢
VS 2019 配置tensorRT生成engine
Agile certification (professional scrum Master) simulation exercise-2
Vs 2019 configuration du moteur de génération de tensorrt
[shutter] monitor the transparency gradient of the scrolling action control component (remove the blank of the top status bar | frame layout component | transparency component | monitor the scrolling
45 lectures on MySQL [index]
docker安装mysql
MySql实战45讲【行锁】
Yiwen takes you to know ZigBee
MySql實戰45講【SQL查詢和更新執行流程】
C language beginner level - pointer explanation - paoding jieniu chapter
随机推荐
Vs Code configure virtual environment
[shutter] monitor the transparency gradient of the scrolling action control component (remove the blank of the top status bar | frame layout component | transparency component | monitor the scrolling
Add some hard dishes to the interview: how to improve throughput and timeliness in delayed task scenarios!
I2C 子系统(一):I2C spec
VS 2019 配置tensorRT生成engine
模糊查询时报错Parameter index out of range (1 > number of parameters, which is 0)
JS finds all the parent nodes or child nodes under a node according to the tree structure
Kubernetes family container housekeeper pod online Q & A?
BigVision代码
PHP constructor with parameters - PHP constructor with a parameter
Creation and destruction of function stack frame
Andwhere multiple or query ORM conditions in yii2
Parameter index out of range (1 > number of parameters, which is 0)
The solution of "the required function is not supported" in win10 remote desktop connection is to modify the Registry [easy to understand]
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)
Change cell color in Excel using C - cell color changing in Excel using C
复选框的使用:全选,全不选,选一部分
从C到Capable-----利用指针作为函数参数求字符串是否为回文字符
QT based tensorrt accelerated yolov5
Process the dataset and use labelencoder to convert all IDs to start from 0