当前位置:网站首页>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 .
边栏推荐
- I2C 子系统(三):I2C Driver
- 内存泄漏工具VLD安装及使用
- PHP constructor with parameters - PHP constructor with a parameter
- 分布式事务
- I2C 子系统(一):I2C spec
- I2C subsystem (I): I2C spec
- Installation and use of memory leak tool VLD
- MySQL practice 45 [global lock and table lock]
- JMeter performance test JDBC request (query database to obtain database data) use "suggestions collection"
- Getting started | jetpack hilt dependency injection framework
猜你喜欢

VS 2019安装及配置opencv

别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!

Installation and use of memory leak tool VLD

docker安装redis

vfork执行时出现Segmentation fault

Deep learning: multi-layer perceptron and XOR problem (pytoch Implementation)

The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled

Can netstat still play like this?

C language beginner level - pointer explanation - paoding jieniu chapter

The process of connecting MySQL with docker
随机推荐
Source code analysis | layout file loading process
I2C 子系统(一):I2C spec
从输入URL到页面展示这中间发生了什么?
Yiwen takes you to know ZigBee
Andwhere multiple or query ORM conditions in yii2
后管中编辑与预览获取表单的值写法
[C语言]给账号密码进行MD5加密
Parameter index out of range (1 > number of parameters, which is 0)
[error record] the parameter 'can't have a value of' null 'because of its type, but the im
PAT乙级常用函数用法总结
JMeter performance test JDBC request (query database to obtain database data) use "suggestions collection"
Update and return document in mongodb - update and return document in mongodb
超好用的日志库 logzero
Can I use read-only to automatically implement properties- Is read-only auto-implemented property possible?
【PyG】理解MessagePassing过程,GCN demo详解
Force freeing memory in PHP
Sqlserver row to column pivot
I2C 子系统(四):I2C debug
How to implement append in tensor
Privatization lightweight continuous integration deployment scheme -- 01 environment configuration (Part 2)