当前位置:网站首页>[question 019: what is the understanding of spherecastcommand in unity?]
[question 019: what is the understanding of spherecastcommand in unity?]
2022-07-26 04:01:00 【valaki】
One 、 background
In the game optimization, the ray detection in physics will be optimized , For example, you will perform the same for multiple players Physics.SphereCast() Radiographic testing , Most of the time , In the process of research and development, we may directly adopt a circular way , Many times Physics.SphereCast() Logical processing ; Here we can use SpherecastCommand replace , combination Job To operate ;
Two 、 The demo 
In the animation above 3 Objects to be detected , The objects here can be added or deleted according to the actual situation ; It will be adjusted according to the actual situation radius 、 Detection distance 、 Detection direction To test ; Different parameters will detect their corresponding results ; among Red Indicates that the object is the point detected by the ray ;
From the above animation, you can dynamically adjust the radius, but the dynamic change of the green part , Similarly, the adjustment of detection distance will also be visualized ;
For specific logic, please refer to the source code ; There are detailed logical comments in the code .
3、 ... and 、 Source code
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Unity.Collections;
using Unity.Mathematics;
using UnityEditor.Timeline;
using UnityEngine;
[ExecuteAlways]
public class TestCommand : MonoBehaviour
{
public List<Transform> transforms;
public List<Material> materials;
public List<MeshRenderer> targetsMeshRenders;
public enum Direction
{
Right,
Left,
Forward,
Back,
}
public float distacne = 1;
public float radius = 1;
int count = 1;
public Direction direction = Direction.Right;
public Vector3 _direction = Vector3.right;
// Update is called once per frame
void Update()
{
//https://docs.unity3d.com/cn/2019.1/ScriptReference/SpherecastCommand.html For details, please refer to the official instructions here
count = transforms.Count;
InitDirection();
RestMaterials();
// Define a RaycastHit Array Used to store RaycastHit Information about here count Indicates the number to be detected
NativeArray<RaycastHit> raycastHits = new NativeArray<RaycastHit>(count, Allocator.TempJob);
// Definition SpherecastCommand Array Represents an array of sphere commands That is, how many commands need to execute sphere ray detection
NativeArray<SpherecastCommand>
spherecastCommands = new NativeArray<SpherecastCommand>(count, Allocator.TempJob);
// The loop here shows how many objects need to perform sphere radiography So how many sphere ray detection commands are created Here we just store the created commands , The specific implementation is later ;
for (int i = 0; i < count; i++)
{
CheckRadius(i);
CheckDistance(i);
CheckDirection(i);
// Create sphere ray casting instructions
/* * The starting position of the projection * Radius of the projected sphere 【scene You can see the green in 】 * direction: Direction of detection 【scene It can be seen that 】 * distance: The distance of detection 【scene It can be seen that 】 */
spherecastCommands[i] =
new SpherecastCommand(transforms[i].position, radius, transforms[i].rotation * _direction, distacne);
}
//https://docs.unity3d.com/cn/2019.1/ScriptReference/SpherecastCommand.ScheduleBatch.html
// Here is the sphere batch projection command that needs to be executed There will be a return here job object And arrange the job here to enter the state of waiting for execution ,
var jobhandel = SpherecastCommand.ScheduleBatch(spherecastCommands, raycastHits, 1, default);
// Wait for the execution of this batch to complete
jobhandel.Complete();
for (int i = 0; i < raycastHits.Length; i++)
{
RaycastHit raycastHit = raycastHits[i];
if (raycastHit.transform != null)
{
raycastHit.transform.GetComponent<MeshRenderer>().sharedMaterial = materials[1];
}
}
// Release
raycastHits.Dispose();
// Release
spherecastCommands.Dispose();
}
void InitDirection()
{
switch (direction)
{
case Direction.Back:
_direction = Vector3.back;
break;
case Direction.Forward:
_direction = Vector3.forward;
break;
case Direction.Left:
_direction = Vector3.left;
break;
case Direction.Right:
_direction = Vector3.right;
break;
}
}
/// <summary>
/// Direction of detection
/// </summary>
/// <param name="index"></param>
void CheckDirection(int index)
{
Debug.DrawLine(transforms[index].position,
transforms[index].position + transforms[index].rotation * _direction * 15, Color.magenta);
}
/// <summary>
/// Radius detection range
/// </summary>
/// <param name="index"></param>
void CheckRadius(int index)
{
Vector3 pos = transforms[index].position;
for (int i = 0; i < 360; i += 5)
{
float x = pos.x + math.cos(i) * radius;
float z = pos.z + math.sin(i) * radius;
Debug.DrawLine(pos, new Vector3(x, pos.y, z), Color.green);
}
}
/// <summary>
/// Distance detection The starting point of distance detection is the radius , Actual detection distance = radius + distance
/// </summary>
/// <param name="index"></param>
void CheckDistance(int index)
{
Vector3 pos = transforms[index].position;
for (int i = 0; i < 360; i += 5)
{
float rx = math.cos(i) * radius;
float ry = math.sin(i) * radius;
float sx = pos.x + rx;
float sz = pos.z + ry;
float ex = sx + math.cos(i) * distacne;
float ey = sz + math.sin(i) * distacne;
Debug.DrawLine(new Vector3(sx, pos.y, sz), new Vector3(ex, pos.y, ey), Color.yellow);
}
}
/// <summary>
/// Reset Materail
/// </summary>
void RestMaterials()
{
foreach (var tmr in targetsMeshRenders)
{
tmr.sharedMaterial = materials[0];
}
}
}
Four 、 Conclusion
It seems that eating too much chili is a little inflamed -【valaki】
边栏推荐
- [Reading Notes - > data analysis] Introduction to BDA textbook data analysis
- SDL2 Opengl遇到的坑
- Dracoo Master天龙卡牌大师
- [cloud native kubernetes] how to use configmap under kubernetes cluster
- Kbpc1510-asemi large chip 15A rectifier bridge kbpc1510
- ZK snark: about private key, ring signature, zkksp
- What are the differences between vite and wenpack?
- Testing is not valued? Senior: you should think in another position
- WAF details
- day03_ 1_ Idea tutorial
猜你喜欢

Supervit for deep learning

MySQL index failure scenarios and Solutions

E-commerce operator Xiaobai, how to get started quickly and learn data analysis?

(翻译)网站流程图和用户流程图的使用时机

Moco V2: further upgrade of Moco series

day03_ 1_ Idea tutorial

cpu和gpu已过时,npu和apu的时代开始

开源许可证的传染性问题浅析

How to use graffiti magic color product development kit

Six years of automated testing from scratch, I don't regret turning development to testing
随机推荐
PHP <=> 太空船运算符(组合比较符)
容器跑不动?网络可不背锅
6年从零开始的自动化测试之路,开发转测试我不后悔...
测试工作不受重视?学长:你应该换位思考
2.9.4 Ext JS的布尔对象类型处理及便捷方法
Apply for SSL certificate, configure SSL certificate for domain name, and deploy server; Download and installation of SSL certificate
Verilog implementation of key dithering elimination
全校软硬件基础设施一站式监控 ,苏州大学以时序数据库替换 PostgreSQL
ZK snark: about private key, ring signature, zkksp
Chinese database oceanbase was selected into the Forrester translational data platform report
涂鸦幻彩产品开发包如何使用
Go Plus Security:一款Build Web3不可或缺的安全生态基础设施
What is the problem of the time series database that has been developed for 5 years?
E-commerce operator Xiaobai, how to get started quickly and learn data analysis?
【云原生】谈谈老牌消息中间件ActiveMQ的理解
Worked overtime for a week to develop a reporting system. This low code free it reporting artifact is very easy to use
How to build an enterprise level OLAP data engine for massive data and high real-time requirements?
General test case writing specification
php 实现从1累加到100的算法
微信小程序实现音乐播放器(5)