consolidate all repos to one for archive

This commit is contained in:
2025-01-28 13:46:42 +01:00
commit a6610fbc7a
5350 changed files with 2705721 additions and 0 deletions

View File

@@ -0,0 +1,61 @@
# This .gitignore file should be placed at the root of your Unity project directory
#
# Get latest from https://github.com/github/gitignore/blob/master/Unity.gitignore
#
[Ll]ibrary/
[Tt]emp/
[Oo]bj/
[Bb]uild/
[Bb]uilds/
[Ll]ogs/
[Mm]emoryCaptures/
[Uu]serSettings/
# Asset meta data should only be ignored when the corresponding asset is also ignored
!/[Aa]ssets/**/*.meta
# Uncomment this line if you wish to ignore the asset store tools plugin
# /[Aa]ssets/AssetStoreTools*
# Autogenerated Jetbrains Rider plugin
[Aa]ssets/Plugins/Editor/JetBrains*
# Visual Studio cache directory
.vs/
# Gradle cache directory
.gradle/
# Autogenerated VS/MD/Consulo solution and project files
ExportedObj/
.consulo/
*.csproj
*.unityproj
*.sln
*.suo
*.tmp
*.user
*.userprefs
*.pidb
*.booproj
*.svd
*.pdb
*.mdb
*.opendb
*.VC.db
# Unity3D generated meta files
*.pidb.meta
*.pdb.meta
*.mdb.meta
# Unity3D generated file on crash reports
sysinfo.txt
# Builds
*.apk
*.unitypackage
# Crashlytics generated file
crashlytics-build.properties

View File

@@ -0,0 +1,4 @@
# roguelike-game
Game that we created during 2. Year, 2. Semester for lecture "Razvoj Programskih Sistemov"
Unitiy 2021.3.22f1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f00519e1c34809d4799de6dc33acf217
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5586b1e7dbff7484faf3c776171e3b10
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 858 B

View File

@@ -0,0 +1,123 @@
fileFormatVersion: 2
guid: b79bf9c11e262b441adf9d6de98e6a3b
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 12
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMasterTextureLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Server
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2fb5d77b873e64613a581792da48ad18
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 579 B

View File

@@ -0,0 +1,159 @@
fileFormatVersion: 2
guid: 0a414e5da4f53da7793ce6e41da00b88
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 12
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMasterTextureLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Server
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: WebGL
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 46722e9c405a05ffbbeaf46430aab94e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1b77dad89fcfdb6458b694704151364d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,216 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &6564949427523009461
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 5780977738279389511}
- component: {fileID: 4655382050640036602}
- component: {fileID: 5755219281317843580}
m_Layer: 0
m_Name: Layer1
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &5780977738279389511
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6564949427523009461}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 2409586854805903430}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1839735485 &4655382050640036602
Tilemap:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6564949427523009461}
m_Enabled: 1
m_Tiles:
- first: {x: -1, y: 0, z: 0}
second:
serializedVersion: 2
m_TileIndex: 0
m_TileSpriteIndex: 0
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
m_AnimatedTiles: {}
m_TileAssetArray:
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: e79ed490e19db1a4dbe1e701aac40c84, type: 2}
m_TileSpriteArray:
- m_RefCount: 1
m_Data: {fileID: 1119223491, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_TileMatrixArray:
- m_RefCount: 1
m_Data:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_TileColorArray:
- m_RefCount: 1
m_Data: {r: 1, g: 1, b: 1, a: 1}
m_TileObjectToInstantiateArray: []
m_AnimationFrameRate: 1
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Origin: {x: -1, y: 0, z: 0}
m_Size: {x: 1, y: 1, z: 1}
m_TileAnchor: {x: 0.5, y: 0.5, z: 0}
m_TileOrientation: 0
m_TileOrientationMatrix:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
--- !u!483693784 &5755219281317843580
TilemapRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6564949427523009461}
m_Enabled: 1
m_CastShadows: 0
m_ReceiveShadows: 0
m_DynamicOccludee: 0
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 0
m_RayTracingMode: 0
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 1
m_SelectedEditorRenderState: 0
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_ChunkSize: {x: 32, y: 32, z: 32}
m_ChunkCullingBounds: {x: 0, y: 0, z: 0}
m_MaxChunkCount: 16
m_MaxFrameAge: 16
m_SortOrder: 0
m_Mode: 0
m_DetectChunkCullingBounds: 0
m_MaskInteraction: 0
--- !u!1 &7307634625435411504
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 2409586854805903430}
- component: {fileID: 8222494970806651979}
m_Layer: 0
m_Name: animatedtilepallet
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 0
--- !u!4 &2409586854805903430
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7307634625435411504}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 5780977738279389511}
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!156049354 &8222494970806651979
Grid:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7307634625435411504}
m_Enabled: 1
m_CellSize: {x: 1, y: 1, z: 0}
m_CellGap: {x: 0, y: 0, z: 0}
m_CellLayout: 0
m_CellSwizzle: 0
--- !u!114 &4801759269006331233
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 12395, guid: 0000000000000000e000000000000000, type: 0}
m_Name: Palette Settings
m_EditorClassIdentifier:
cellSizing: 0
m_TransparencySortMode: 0
m_TransparencySortAxis: {x: 0, y: 0, z: 1}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 2e8113a40b0ec1a499a8232459db921d
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}
m_Name: box
m_EditorClassIdentifier:
m_Sprite: {fileID: -1126250345, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Transform:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_InstancedGameObject: {fileID: 0}
m_Flags: 1
m_ColliderType: 1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 99f529ef1fec8af4eb428cd637aa88c4
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}
m_Name: box2
m_EditorClassIdentifier:
m_Sprite: {fileID: 1900342383, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Transform:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_InstancedGameObject: {fileID: 0}
m_Flags: 1
m_ColliderType: 1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 78d0803d6a8060c459f21b8984901979
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}
m_Name: box3
m_EditorClassIdentifier:
m_Sprite: {fileID: 768237871, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Transform:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_InstancedGameObject: {fileID: 0}
m_Flags: 1
m_ColliderType: 1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 15d5e75536df06645abfab88049cd23f
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}
m_Name: box4
m_EditorClassIdentifier:
m_Sprite: {fileID: -870893999, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Transform:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_InstancedGameObject: {fileID: 0}
m_Flags: 1
m_ColliderType: 1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 9ff8462e8187bf943b33ecba921f018c
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}
m_Name: box5
m_EditorClassIdentifier:
m_Sprite: {fileID: 1356700150, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Transform:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_InstancedGameObject: {fileID: 0}
m_Flags: 1
m_ColliderType: 1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a9e9113edb75c5c4b86c12f8f6193772
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}
m_Name: box6
m_EditorClassIdentifier:
m_Sprite: {fileID: 856969336, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Transform:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_InstancedGameObject: {fileID: 0}
m_Flags: 1
m_ColliderType: 1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b4a5737fc16da2345ba0adcc9acc8299
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}
m_Name: box7
m_EditorClassIdentifier:
m_Sprite: {fileID: 1844356825, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Transform:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_InstancedGameObject: {fileID: 0}
m_Flags: 1
m_ColliderType: 1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ee34632ad0ff78945a81b6c87e01918a
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,216 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &2611076796529328546
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 8511960252818152009}
- component: {fileID: 3190624230189261742}
m_Layer: 0
m_Name: breakabletilepallet
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &8511960252818152009
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2611076796529328546}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 7036695458135302325}
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!156049354 &3190624230189261742
Grid:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2611076796529328546}
m_Enabled: 1
m_CellSize: {x: 1, y: 1, z: 0}
m_CellGap: {x: 0, y: 0, z: 0}
m_CellLayout: 0
m_CellSwizzle: 0
--- !u!1 &6776719409454517759
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 7036695458135302325}
- component: {fileID: 3835123624615451699}
- component: {fileID: 6448151840857947069}
m_Layer: 0
m_Name: Layer1
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &7036695458135302325
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6776719409454517759}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 8511960252818152009}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1839735485 &3835123624615451699
Tilemap:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6776719409454517759}
m_Enabled: 1
m_Tiles:
- first: {x: -1, y: 0, z: 0}
second:
serializedVersion: 2
m_TileIndex: 0
m_TileSpriteIndex: 0
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
m_AnimatedTiles: {}
m_TileAssetArray:
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: 9ff8462e8187bf943b33ecba921f018c, type: 2}
m_TileSpriteArray:
- m_RefCount: 1
m_Data: {fileID: -870893999, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_TileMatrixArray:
- m_RefCount: 1
m_Data:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_TileColorArray:
- m_RefCount: 1
m_Data: {r: 1, g: 1, b: 1, a: 1}
m_TileObjectToInstantiateArray: []
m_AnimationFrameRate: 1
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Origin: {x: -1, y: 0, z: 0}
m_Size: {x: 1, y: 1, z: 1}
m_TileAnchor: {x: 0.5, y: 0.5, z: 0}
m_TileOrientation: 0
m_TileOrientationMatrix:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
--- !u!483693784 &6448151840857947069
TilemapRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6776719409454517759}
m_Enabled: 1
m_CastShadows: 0
m_ReceiveShadows: 0
m_DynamicOccludee: 0
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 0
m_RayTracingMode: 0
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 1
m_SelectedEditorRenderState: 0
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_ChunkSize: {x: 32, y: 32, z: 32}
m_ChunkCullingBounds: {x: 0, y: 0, z: 0}
m_MaxChunkCount: 16
m_MaxFrameAge: 16
m_SortOrder: 0
m_Mode: 0
m_DetectChunkCullingBounds: 0
m_MaskInteraction: 0
--- !u!114 &1090440711294975296
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 12395, guid: 0000000000000000e000000000000000, type: 0}
m_Name: Palette Settings
m_EditorClassIdentifier:
cellSizing: 0
m_TransparencySortMode: 0
m_TransparencySortAxis: {x: 0, y: 0, z: 1}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 2c05cfb934b12934a81c7224a4d183fe
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}
m_Name: cross
m_EditorClassIdentifier:
m_Sprite: {fileID: 1119223491, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Transform:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_InstancedGameObject: {fileID: 0}
m_Flags: 1
m_ColliderType: 1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e79ed490e19db1a4dbe1e701aac40c84
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}
m_Name: mech
m_EditorClassIdentifier:
m_Sprite: {fileID: 1958027655, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Transform:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_InstancedGameObject: {fileID: 0}
m_Flags: 1
m_ColliderType: 1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 79760447b8286d3488af7b6870151807
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}
m_Name: rocks
m_EditorClassIdentifier:
m_Sprite: {fileID: 1136252074, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Transform:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_InstancedGameObject: {fileID: 0}
m_Flags: 1
m_ColliderType: 1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8a02a9551d6625f47aa5cb16f95306a2
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}
m_Name: spikes
m_EditorClassIdentifier:
m_Sprite: {fileID: 1109879464, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Transform:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_InstancedGameObject: {fileID: 0}
m_Flags: 1
m_ColliderType: 1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: cade8dbab6c65874a98c8bed2f40288d
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,372 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &615314453609837212
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 2692404104619394634}
- component: {fileID: 9169250136737427970}
- component: {fileID: 7441959983015684952}
m_Layer: 0
m_Name: Layer1
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &2692404104619394634
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 615314453609837212}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4627062475030868754}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1839735485 &9169250136737427970
Tilemap:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 615314453609837212}
m_Enabled: 1
m_Tiles:
- first: {x: -3, y: -3, z: 0}
second:
serializedVersion: 2
m_TileIndex: 9
m_TileSpriteIndex: 9
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
- first: {x: -2, y: -3, z: 0}
second:
serializedVersion: 2
m_TileIndex: 10
m_TileSpriteIndex: 10
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
- first: {x: -1, y: -3, z: 0}
second:
serializedVersion: 2
m_TileIndex: 11
m_TileSpriteIndex: 11
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
- first: {x: -3, y: -2, z: 0}
second:
serializedVersion: 2
m_TileIndex: 2
m_TileSpriteIndex: 2
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
- first: {x: -2, y: -2, z: 0}
second:
serializedVersion: 2
m_TileIndex: 7
m_TileSpriteIndex: 7
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
- first: {x: -1, y: -2, z: 0}
second:
serializedVersion: 2
m_TileIndex: 8
m_TileSpriteIndex: 8
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
- first: {x: -3, y: -1, z: 0}
second:
serializedVersion: 2
m_TileIndex: 5
m_TileSpriteIndex: 5
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
- first: {x: -2, y: -1, z: 0}
second:
serializedVersion: 2
m_TileIndex: 4
m_TileSpriteIndex: 4
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
- first: {x: -1, y: -1, z: 0}
second:
serializedVersion: 2
m_TileIndex: 1
m_TileSpriteIndex: 1
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
- first: {x: -3, y: 0, z: 0}
second:
serializedVersion: 2
m_TileIndex: 6
m_TileSpriteIndex: 6
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
- first: {x: -2, y: 0, z: 0}
second:
serializedVersion: 2
m_TileIndex: 3
m_TileSpriteIndex: 3
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
- first: {x: -1, y: 0, z: 0}
second:
serializedVersion: 2
m_TileIndex: 0
m_TileSpriteIndex: 0
m_TileMatrixIndex: 0
m_TileColorIndex: 0
m_TileObjectToInstantiateIndex: 65535
dummyAlignment: 0
m_AllTileFlags: 1073741825
m_AnimatedTiles: {}
m_TileAssetArray:
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: d1cfca6ec88c0b249a3e1031b30f0393, type: 2}
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: 99f529ef1fec8af4eb428cd637aa88c4, type: 2}
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: 79760447b8286d3488af7b6870151807, type: 2}
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: e79ed490e19db1a4dbe1e701aac40c84, type: 2}
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: 78d0803d6a8060c459f21b8984901979, type: 2}
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: 15d5e75536df06645abfab88049cd23f, type: 2}
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: 9ff8462e8187bf943b33ecba921f018c, type: 2}
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: a9e9113edb75c5c4b86c12f8f6193772, type: 2}
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: b4a5737fc16da2345ba0adcc9acc8299, type: 2}
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: cade8dbab6c65874a98c8bed2f40288d, type: 2}
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: ee34632ad0ff78945a81b6c87e01918a, type: 2}
- m_RefCount: 1
m_Data: {fileID: 11400000, guid: 8a02a9551d6625f47aa5cb16f95306a2, type: 2}
m_TileSpriteArray:
- m_RefCount: 1
m_Data: {fileID: -549465545, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
- m_RefCount: 1
m_Data: {fileID: -1126250345, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
- m_RefCount: 1
m_Data: {fileID: 1958027655, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
- m_RefCount: 1
m_Data: {fileID: 1119223491, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
- m_RefCount: 1
m_Data: {fileID: 1900342383, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
- m_RefCount: 1
m_Data: {fileID: 768237871, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
- m_RefCount: 1
m_Data: {fileID: -870893999, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
- m_RefCount: 1
m_Data: {fileID: 1356700150, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
- m_RefCount: 1
m_Data: {fileID: 856969336, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
- m_RefCount: 1
m_Data: {fileID: 1109879464, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
- m_RefCount: 1
m_Data: {fileID: 1844356825, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
- m_RefCount: 1
m_Data: {fileID: 1136252074, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_TileMatrixArray:
- m_RefCount: 12
m_Data:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_TileColorArray:
- m_RefCount: 12
m_Data: {r: 1, g: 1, b: 1, a: 1}
- m_RefCount: 0
m_Data: {r: NaN, g: NaN, b: NaN, a: NaN}
m_TileObjectToInstantiateArray: []
m_AnimationFrameRate: 1
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Origin: {x: -3, y: -3, z: 0}
m_Size: {x: 3, y: 4, z: 1}
m_TileAnchor: {x: 0.5, y: 0.5, z: 0}
m_TileOrientation: 0
m_TileOrientationMatrix:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
--- !u!483693784 &7441959983015684952
TilemapRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 615314453609837212}
m_Enabled: 1
m_CastShadows: 0
m_ReceiveShadows: 0
m_DynamicOccludee: 0
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 0
m_RayTracingMode: 0
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 1
m_SelectedEditorRenderState: 0
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_ChunkSize: {x: 32, y: 32, z: 32}
m_ChunkCullingBounds: {x: 0, y: 0, z: 0}
m_MaxChunkCount: 16
m_MaxFrameAge: 16
m_SortOrder: 0
m_Mode: 0
m_DetectChunkCullingBounds: 0
m_MaskInteraction: 0
--- !u!1 &8075856021441697299
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4627062475030868754}
- component: {fileID: 2313063800536819355}
m_Layer: 0
m_Name: tilepallet
m_TagString: Collider
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4627062475030868754
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8075856021441697299}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 2692404104619394634}
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!156049354 &2313063800536819355
Grid:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8075856021441697299}
m_Enabled: 1
m_CellSize: {x: 1, y: 1, z: 0}
m_CellGap: {x: 0, y: 0, z: 0}
m_CellLayout: 0
m_CellSwizzle: 0
--- !u!114 &6172809620290739992
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 12395, guid: 0000000000000000e000000000000000, type: 0}
m_Name: Palette Settings
m_EditorClassIdentifier:
cellSizing: 0
m_TransparencySortMode: 0
m_TransparencySortAxis: {x: 0, y: 0, z: 1}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 793b2865cc4ccd64d998aa9ad8d24d7d
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

View File

@@ -0,0 +1,36 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}
m_Name: wall
m_EditorClassIdentifier:
m_Sprite: {fileID: -549465545, guid: 9f72a4a0113fa2642b3b15907c65c473, type: 3}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Transform:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_InstancedGameObject: {fileID: 0}
m_Flags: 1
m_ColliderType: 1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d1cfca6ec88c0b249a3e1031b30f0393
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6942e1e80e8b54fde9147e843f1bec4f

View File

@@ -0,0 +1,8 @@
{
"name": "AstarPathfindingProject",
"references": [],
"optionalUnityReferences": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: efa45043feb7e4147a305b73b5cea642
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 5eeb3c5df5ca840d3ae6b93e6b207d74
folderAsset: yes
timeCreated: 1497206641
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,40 @@
using UnityEngine;
using System.Collections;
namespace Pathfinding {
/// <summary>
/// Sets the destination of an AI to the position of a specified object.
/// This component should be attached to a GameObject together with a movement script such as AIPath, RichAI or AILerp.
/// This component will then make the AI move towards the <see cref="target"/> set on this component.
///
/// See: <see cref="Pathfinding.IAstarAI.destination"/>
///
/// [Open online documentation to see images]
/// </summary>
[UniqueComponent(tag = "ai.destination")]
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_a_i_destination_setter.php")]
public class AIDestinationSetter : VersionedMonoBehaviour {
/// <summary>The object that the AI should move to</summary>
public Transform target;
IAstarAI ai;
void OnEnable () {
ai = GetComponent<IAstarAI>();
// Update the destination right before searching for a path as well.
// This is enough in theory, but this script will also update the destination every
// frame as the destination is used for debugging and may be used for other things by other
// scripts as well. So it makes sense that it is up to date every frame.
if (ai != null) ai.onSearchPath += Update;
}
void OnDisable () {
if (ai != null) ai.onSearchPath -= Update;
}
/// <summary>Updates the AI's destination every frame</summary>
void Update () {
if (target != null && ai != null) ai.destination = target.position;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: c9679e68a0f1144e79c664d9a11ca121
timeCreated: 1495015523
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,59 @@
using UnityEngine;
using System.Collections;
namespace Pathfinding {
/// <summary>
/// Simple patrol behavior.
/// This will set the destination on the agent so that it moves through the sequence of objects in the <see cref="targets"/> array.
/// Upon reaching a target it will wait for <see cref="delay"/> seconds.
///
/// See: <see cref="Pathfinding.AIDestinationSetter"/>
/// See: <see cref="Pathfinding.AIPath"/>
/// See: <see cref="Pathfinding.RichAI"/>
/// See: <see cref="Pathfinding.AILerp"/>
/// </summary>
[UniqueComponent(tag = "ai.destination")]
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_patrol.php")]
public class Patrol : VersionedMonoBehaviour {
/// <summary>Target points to move to in order</summary>
public Transform[] targets;
/// <summary>Time in seconds to wait at each target</summary>
public float delay = 0;
/// <summary>Current target index</summary>
int index;
IAstarAI agent;
float switchTime = float.PositiveInfinity;
protected override void Awake () {
base.Awake();
agent = GetComponent<IAstarAI>();
}
/// <summary>Update is called once per frame</summary>
void Update () {
if (targets.Length == 0) return;
bool search = false;
// Note: using reachedEndOfPath and pathPending instead of reachedDestination here because
// if the destination cannot be reached by the agent, we don't want it to get stuck, we just want it to get as close as possible and then move on.
if (agent.reachedEndOfPath && !agent.pathPending && float.IsPositiveInfinity(switchTime)) {
switchTime = Time.time + delay;
}
if (Time.time >= switchTime) {
index = index + 1;
search = true;
switchTime = float.PositiveInfinity;
}
index = index % targets.Length;
agent.destination = targets[index].position;
if (search) agent.SearchPath();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 22e6c29e32504465faa943c537d8029b
timeCreated: 1495286303
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: e271255bdfe8941f9ab0acccbb14dd82
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b6b8abb917bca4ce0ad1b26452b3c58d

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5ab9be352d07b44e68ad7c1a03eef3a5

View File

@@ -0,0 +1,774 @@
using UnityEngine;
using System.Collections;
using UnityEngine.Serialization;
namespace Pathfinding {
using Pathfinding.RVO;
using Pathfinding.Util;
/// <summary>
/// Base class for AIPath and RichAI.
/// This class holds various methods and fields that are common to both AIPath and RichAI.
///
/// See: <see cref="Pathfinding.AIPath"/>
/// See: <see cref="Pathfinding.RichAI"/>
/// See: <see cref="Pathfinding.IAstarAI"/> (all movement scripts implement this interface)
/// </summary>
[RequireComponent(typeof(Seeker))]
public abstract class AIBase : VersionedMonoBehaviour {
/// <summary>\copydoc Pathfinding::IAstarAI::radius</summary>
public float radius = 0.5f;
/// <summary>\copydoc Pathfinding::IAstarAI::height</summary>
public float height = 2;
/// <summary>
/// Determines how often the agent will search for new paths (in seconds).
/// The agent will plan a new path to the target every N seconds.
///
/// If you have fast moving targets or AIs, you might want to set it to a lower value.
///
/// See: <see cref="shouldRecalculatePath"/>
/// See: <see cref="SearchPath"/>
///
/// Deprecated: This has been renamed to \reflink{autoRepath.interval}.
/// See: \reflink{AutoRepathPolicy}
/// </summary>
public float repathRate {
get {
return this.autoRepath.interval;
}
set {
this.autoRepath.interval = value;
}
}
/// <summary>
/// \copydoc Pathfinding::IAstarAI::canSearch
/// Deprecated: This has been superseded by \reflink{autoRepath.mode}.
/// </summary>
public bool canSearch {
get {
return this.autoRepath.mode != AutoRepathPolicy.Mode.Never;
}
set {
if (value) {
if (this.autoRepath.mode == AutoRepathPolicy.Mode.Never) {
this.autoRepath.mode = AutoRepathPolicy.Mode.EveryNSeconds;
}
} else {
this.autoRepath.mode = AutoRepathPolicy.Mode.Never;
}
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::canMove</summary>
public bool canMove = true;
/// <summary>Max speed in world units per second</summary>
[UnityEngine.Serialization.FormerlySerializedAs("speed")]
public float maxSpeed = 1;
/// <summary>
/// Gravity to use.
/// If set to (NaN,NaN,NaN) then Physics.Gravity (configured in the Unity project settings) will be used.
/// If set to (0,0,0) then no gravity will be used and no raycast to check for ground penetration will be performed.
/// </summary>
public Vector3 gravity = new Vector3(float.NaN, float.NaN, float.NaN);
/// <summary>
/// Layer mask to use for ground placement.
/// Make sure this does not include the layer of any colliders attached to this gameobject.
///
/// See: <see cref="gravity"/>
/// See: https://docs.unity3d.com/Manual/Layers.html
/// </summary>
public LayerMask groundMask = -1;
/// <summary>
/// Offset along the Y coordinate for the ground raycast start position.
/// Normally the pivot of the character is at the character's feet, but you usually want to fire the raycast
/// from the character's center, so this value should be half of the character's height.
///
/// A green gizmo line will be drawn upwards from the pivot point of the character to indicate where the raycast will start.
///
/// See: <see cref="gravity"/>
/// Deprecated: Use the <see cref="height"/> property instead (2x this value)
/// </summary>
[System.Obsolete("Use the height property instead (2x this value)")]
public float centerOffset {
get { return height * 0.5f; } set { height = value * 2; }
}
[SerializeField]
[HideInInspector]
[FormerlySerializedAs("centerOffset")]
float centerOffsetCompatibility = float.NaN;
[SerializeField]
[HideInInspector]
[UnityEngine.Serialization.FormerlySerializedAs("repathRate")]
float repathRateCompatibility = float.NaN;
[SerializeField]
[HideInInspector]
[UnityEngine.Serialization.FormerlySerializedAs("canSearch")]
[UnityEngine.Serialization.FormerlySerializedAs("repeatedlySearchPaths")]
bool canSearchCompability = false;
/// <summary>
/// Determines which direction the agent moves in.
/// For 3D games you most likely want the ZAxisIsForward option as that is the convention for 3D games.
/// For 2D games you most likely want the YAxisIsForward option as that is the convention for 2D games.
///
/// Using the YAxisForward option will also allow the agent to assume that the movement will happen in the 2D (XY) plane instead of the XZ plane
/// if it does not know. This is important only for the point graph which does not have a well defined up direction. The other built-in graphs (e.g the grid graph)
/// will all tell the agent which movement plane it is supposed to use.
///
/// [Open online documentation to see images]
/// </summary>
[UnityEngine.Serialization.FormerlySerializedAs("rotationIn2D")]
public OrientationMode orientation = OrientationMode.ZAxisForward;
/// <summary>
/// If true, the forward axis of the character will be along the Y axis instead of the Z axis.
///
/// Deprecated: Use <see cref="orientation"/> instead
/// </summary>
[System.Obsolete("Use orientation instead")]
public bool rotationIn2D {
get { return orientation == OrientationMode.YAxisForward; }
set { orientation = value ? OrientationMode.YAxisForward : OrientationMode.ZAxisForward; }
}
/// <summary>
/// If true, the AI will rotate to face the movement direction.
/// See: <see cref="orientation"/>
/// </summary>
public bool enableRotation = true;
/// <summary>
/// Position of the agent.
/// If <see cref="updatePosition"/> is true then this value will be synchronized every frame with Transform.position.
/// </summary>
protected Vector3 simulatedPosition;
/// <summary>
/// Rotation of the agent.
/// If <see cref="updateRotation"/> is true then this value will be synchronized every frame with Transform.rotation.
/// </summary>
protected Quaternion simulatedRotation;
/// <summary>
/// Position of the agent.
/// In world space.
/// If <see cref="updatePosition"/> is true then this value is idential to transform.position.
/// See: <see cref="Teleport"/>
/// See: <see cref="Move"/>
/// </summary>
public Vector3 position { get { return updatePosition ? tr.position : simulatedPosition; } }
/// <summary>
/// Rotation of the agent.
/// If <see cref="updateRotation"/> is true then this value is identical to transform.rotation.
/// </summary>
public Quaternion rotation {
get { return updateRotation ? tr.rotation : simulatedRotation; }
set {
if (updateRotation) {
tr.rotation = value;
} else {
simulatedRotation = value;
}
}
}
/// <summary>Accumulated movement deltas from the <see cref="Move"/> method</summary>
Vector3 accumulatedMovementDelta = Vector3.zero;
/// <summary>
/// Current desired velocity of the agent (does not include local avoidance and physics).
/// Lies in the movement plane.
/// </summary>
protected Vector2 velocity2D;
/// <summary>
/// Velocity due to gravity.
/// Perpendicular to the movement plane.
///
/// When the agent is grounded this may not accurately reflect the velocity of the agent.
/// It may be non-zero even though the agent is not moving.
/// </summary>
protected float verticalVelocity;
/// <summary>Cached Seeker component</summary>
protected Seeker seeker;
/// <summary>Cached Transform component</summary>
protected Transform tr;
/// <summary>Cached Rigidbody component</summary>
protected Rigidbody rigid;
/// <summary>Cached Rigidbody component</summary>
protected Rigidbody2D rigid2D;
/// <summary>Cached CharacterController component</summary>
protected CharacterController controller;
/// <summary>
/// Plane which this agent is moving in.
/// This is used to convert between world space and a movement plane to make it possible to use this script in
/// both 2D games and 3D games.
/// </summary>
public IMovementPlane movementPlane = GraphTransform.identityTransform;
/// <summary>
/// Determines if the character's position should be coupled to the Transform's position.
/// If false then all movement calculations will happen as usual, but the object that this component is attached to will not move
/// instead only the <see cref="position"/> property will change.
///
/// This is useful if you want to control the movement of the character using some other means such
/// as for example root motion but still want the AI to move freely.
/// See: Combined with calling <see cref="MovementUpdate"/> from a separate script instead of it being called automatically one can take a similar approach to what is documented here: https://docs.unity3d.com/Manual/nav-CouplingAnimationAndNavigation.html
///
/// See: <see cref="canMove"/> which in contrast to this field will disable all movement calculations.
/// See: <see cref="updateRotation"/>
/// </summary>
[System.NonSerialized]
public bool updatePosition = true;
/// <summary>
/// Determines if the character's rotation should be coupled to the Transform's rotation.
/// If false then all movement calculations will happen as usual, but the object that this component is attached to will not rotate
/// instead only the <see cref="rotation"/> property will change.
///
/// See: <see cref="updatePosition"/>
/// </summary>
[System.NonSerialized]
public bool updateRotation = true;
/// <summary>
/// Determines how the agent recalculates its path automatically.
/// This corresponds to the settings under the "Recalculate Paths Automatically" field in the inspector.
/// </summary>
public AutoRepathPolicy autoRepath = new AutoRepathPolicy();
/// <summary>Indicates if gravity is used during this frame</summary>
protected bool usingGravity { get; set; }
/// <summary>Delta time used for movement during the last frame</summary>
protected float lastDeltaTime;
/// <summary>Last frame index when <see cref="prevPosition1"/> was updated</summary>
protected int prevFrame;
/// <summary>Position of the character at the end of the last frame</summary>
protected Vector3 prevPosition1;
/// <summary>Position of the character at the end of the frame before the last frame</summary>
protected Vector3 prevPosition2;
/// <summary>Amount which the character wants or tried to move with during the last frame</summary>
protected Vector2 lastDeltaPosition;
/// <summary>Only when the previous path has been calculated should the script consider searching for a new path</summary>
protected bool waitingForPathCalculation = false;
[UnityEngine.Serialization.FormerlySerializedAs("target")][SerializeField][HideInInspector]
Transform targetCompatibility;
/// <summary>
/// True if the Start method has been executed.
/// Used to test if coroutines should be started in OnEnable to prevent calculating paths
/// in the awake stage (or rather before start on frame 0).
/// </summary>
bool startHasRun = false;
/// <summary>
/// Target to move towards.
/// The AI will try to follow/move towards this target.
/// It can be a point on the ground where the player has clicked in an RTS for example, or it can be the player object in a zombie game.
///
/// Deprecated: In 4.1 this will automatically add a <see cref="Pathfinding.AIDestinationSetter"/> component and set the target on that component.
/// Try instead to use the <see cref="destination"/> property which does not require a transform to be created as the target or use
/// the AIDestinationSetter component directly.
/// </summary>
[System.Obsolete("Use the destination property or the AIDestinationSetter component instead")]
public Transform target {
get {
var setter = GetComponent<AIDestinationSetter>();
return setter != null ? setter.target : null;
}
set {
targetCompatibility = null;
var setter = GetComponent<AIDestinationSetter>();
if (setter == null) setter = gameObject.AddComponent<AIDestinationSetter>();
setter.target = value;
destination = value != null ? value.position : new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::destination</summary>
public Vector3 destination { get; set; }
/// <summary>\copydoc Pathfinding::IAstarAI::velocity</summary>
public Vector3 velocity {
get {
return lastDeltaTime > 0.000001f ? (prevPosition1 - prevPosition2) / lastDeltaTime : Vector3.zero;
}
}
/// <summary>
/// Velocity that this agent wants to move with.
/// Includes gravity and local avoidance if applicable.
/// </summary>
public Vector3 desiredVelocity { get { return lastDeltaTime > 0.00001f ? movementPlane.ToWorld(lastDeltaPosition / lastDeltaTime, verticalVelocity) : Vector3.zero; } }
/// <summary>\copydoc Pathfinding::IAstarAI::isStopped</summary>
public bool isStopped { get; set; }
/// <summary>\copydoc Pathfinding::IAstarAI::onSearchPath</summary>
public System.Action onSearchPath { get; set; }
/// <summary>True if the path should be automatically recalculated as soon as possible</summary>
protected virtual bool shouldRecalculatePath {
get {
return !waitingForPathCalculation && autoRepath.ShouldRecalculatePath((IAstarAI)this);
}
}
protected AIBase () {
// Note that this needs to be set here in the constructor and not in e.g Awake
// because it is possible that other code runs and sets the destination property
// before the Awake method on this script runs.
destination = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
}
/// <summary>
/// Looks for any attached components like RVOController and CharacterController etc.
///
/// This is done during <see cref="OnEnable"/>. If you are adding/removing components during runtime you may want to call this function
/// to make sure that this script finds them. It is unfortunately prohibitive from a performance standpoint to look for components every frame.
/// </summary>
public virtual void FindComponents () {
tr = transform;
seeker = GetComponent<Seeker>();
// Find attached movement components
controller = GetComponent<CharacterController>();
rigid = GetComponent<Rigidbody>();
rigid2D = GetComponent<Rigidbody2D>();
}
/// <summary>Called when the component is enabled</summary>
protected virtual void OnEnable () {
FindComponents();
// Make sure we receive callbacks when paths are calculated
seeker.pathCallback += OnPathComplete;
Init();
}
/// <summary>
/// Starts searching for paths.
/// If you override this method you should in most cases call base.Start () at the start of it.
/// See: <see cref="Init"/>
/// </summary>
protected virtual void Start () {
startHasRun = true;
Init();
}
void Init () {
if (startHasRun) {
// Clamp the agent to the navmesh (which is what the Teleport call will do essentially. Though only some movement scripts require this, like RichAI).
// The Teleport call will also make sure some variables are properly initialized (like #prevPosition1 and #prevPosition2)
if (canMove) Teleport(position, false);
autoRepath.Reset();
if (shouldRecalculatePath) SearchPath();
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::Teleport</summary>
public virtual void Teleport (Vector3 newPosition, bool clearPath = true) {
if (clearPath) ClearPath();
prevPosition1 = prevPosition2 = simulatedPosition = newPosition;
if (updatePosition) tr.position = newPosition;
if (clearPath) SearchPath();
}
protected void CancelCurrentPathRequest () {
waitingForPathCalculation = false;
// Abort calculation of the current path
if (seeker != null) seeker.CancelCurrentPathRequest();
}
protected virtual void OnDisable () {
ClearPath();
// Make sure we no longer receive callbacks when paths complete
seeker.pathCallback -= OnPathComplete;
velocity2D = Vector3.zero;
accumulatedMovementDelta = Vector3.zero;
verticalVelocity = 0f;
lastDeltaTime = 0;
}
/// <summary>
/// Called every frame.
/// If no rigidbodies are used then all movement happens here.
/// </summary>
protected virtual void Update () {
if (shouldRecalculatePath) SearchPath();
// If gravity is used depends on a lot of things.
// For example when a non-kinematic rigidbody is used then the rigidbody will apply the gravity itself
// Note that the gravity can contain NaN's, which is why the comparison uses !(a==b) instead of just a!=b.
usingGravity = !(gravity == Vector3.zero) && (!updatePosition || ((rigid == null || rigid.isKinematic) && (rigid2D == null || rigid2D.isKinematic)));
if (rigid == null && rigid2D == null && canMove) {
Vector3 nextPosition;
Quaternion nextRotation;
MovementUpdate(Time.deltaTime, out nextPosition, out nextRotation);
FinalizeMovement(nextPosition, nextRotation);
}
}
/// <summary>
/// Called every physics update.
/// If rigidbodies are used then all movement happens here.
/// </summary>
protected virtual void FixedUpdate () {
if (!(rigid == null && rigid2D == null) && canMove) {
Vector3 nextPosition;
Quaternion nextRotation;
MovementUpdate(Time.fixedDeltaTime, out nextPosition, out nextRotation);
FinalizeMovement(nextPosition, nextRotation);
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::MovementUpdate</summary>
public void MovementUpdate (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) {
lastDeltaTime = deltaTime;
MovementUpdateInternal(deltaTime, out nextPosition, out nextRotation);
}
/// <summary>Called during either Update or FixedUpdate depending on if rigidbodies are used for movement or not</summary>
protected abstract void MovementUpdateInternal(float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation);
/// <summary>
/// Outputs the start point and end point of the next automatic path request.
/// This is a separate method to make it easy for subclasses to swap out the endpoints
/// of path requests. For example the <see cref="LocalSpaceRichAI"/> script which requires the endpoints
/// to be transformed to graph space first.
/// </summary>
protected virtual void CalculatePathRequestEndpoints (out Vector3 start, out Vector3 end) {
start = GetFeetPosition();
end = destination;
}
/// <summary>\copydoc Pathfinding::IAstarAI::SearchPath</summary>
public virtual void SearchPath () {
if (float.IsPositiveInfinity(destination.x)) return;
if (onSearchPath != null) onSearchPath();
Vector3 start, end;
CalculatePathRequestEndpoints(out start, out end);
// Request a path to be calculated from our current position to the destination
ABPath p = ABPath.Construct(start, end, null);
SetPath(p);
}
/// <summary>
/// Position of the base of the character.
/// This is used for pathfinding as the character's pivot point is sometimes placed
/// at the center of the character instead of near the feet. In a building with multiple floors
/// the center of a character may in some scenarios be closer to the navmesh on the floor above
/// than to the floor below which could cause an incorrect path to be calculated.
/// To solve this the start point of the requested paths is always at the base of the character.
/// </summary>
public virtual Vector3 GetFeetPosition () {
return position;
}
/// <summary>Called when a requested path has been calculated</summary>
protected abstract void OnPathComplete(Path newPath);
/// <summary>
/// Clears the current path of the agent.
///
/// Usually invoked using <see cref="SetPath(null)"/>
///
/// See: <see cref="SetPath"/>
/// See: <see cref="isStopped"/>
/// </summary>
protected abstract void ClearPath();
/// <summary>\copydoc Pathfinding::IAstarAI::SetPath</summary>
public void SetPath (Path path) {
if (path == null) {
CancelCurrentPathRequest();
ClearPath();
} else if (path.PipelineState == PathState.Created) {
// Path has not started calculation yet
waitingForPathCalculation = true;
seeker.CancelCurrentPathRequest();
seeker.StartPath(path);
autoRepath.DidRecalculatePath(destination);
} else if (path.PipelineState == PathState.Returned) {
// Path has already been calculated
// We might be calculating another path at the same time, and we don't want that path to override this one. So cancel it.
if (seeker.GetCurrentPath() != path) seeker.CancelCurrentPathRequest();
else throw new System.ArgumentException("If you calculate the path using seeker.StartPath then this script will pick up the calculated path anyway as it listens for all paths the Seeker finishes calculating. You should not call SetPath in that case.");
OnPathComplete(path);
} else {
// Path calculation has been started, but it is not yet complete. Cannot really handle this.
throw new System.ArgumentException("You must call the SetPath method with a path that either has been completely calculated or one whose path calculation has not been started at all. It looks like the path calculation for the path you tried to use has been started, but is not yet finished.");
}
}
/// <summary>
/// Accelerates the agent downwards.
/// See: <see cref="verticalVelocity"/>
/// See: <see cref="gravity"/>
/// </summary>
protected void ApplyGravity (float deltaTime) {
// Apply gravity
if (usingGravity) {
float verticalGravity;
velocity2D += movementPlane.ToPlane(deltaTime * (float.IsNaN(gravity.x) ? Physics.gravity : gravity), out verticalGravity);
verticalVelocity += verticalGravity;
} else {
verticalVelocity = 0;
}
}
/// <summary>Calculates how far to move during a single frame</summary>
protected Vector2 CalculateDeltaToMoveThisFrame (Vector2 position, float distanceToEndOfPath, float deltaTime) {
// Direction and distance to move during this frame
return Vector2.ClampMagnitude(velocity2D * deltaTime, distanceToEndOfPath);
}
/// <summary>
/// Simulates rotating the agent towards the specified direction and returns the new rotation.
///
/// Note that this only calculates a new rotation, it does not change the actual rotation of the agent.
/// Useful when you are handling movement externally using <see cref="FinalizeMovement"/> but you want to use the built-in rotation code.
///
/// See: <see cref="orientation"/>
/// </summary>
/// <param name="direction">Direction in world space to rotate towards.</param>
/// <param name="maxDegrees">Maximum number of degrees to rotate this frame.</param>
public Quaternion SimulateRotationTowards (Vector3 direction, float maxDegrees) {
return SimulateRotationTowards(movementPlane.ToPlane(direction), maxDegrees);
}
/// <summary>
/// Simulates rotating the agent towards the specified direction and returns the new rotation.
///
/// Note that this only calculates a new rotation, it does not change the actual rotation of the agent.
///
/// See: <see cref="orientation"/>
/// See: <see cref="movementPlane"/>
/// </summary>
/// <param name="direction">Direction in the movement plane to rotate towards.</param>
/// <param name="maxDegrees">Maximum number of degrees to rotate this frame.</param>
protected Quaternion SimulateRotationTowards (Vector2 direction, float maxDegrees) {
if (direction != Vector2.zero) {
Quaternion targetRotation = Quaternion.LookRotation(movementPlane.ToWorld(direction, 0), movementPlane.ToWorld(Vector2.zero, 1));
// This causes the character to only rotate around the Z axis
if (orientation == OrientationMode.YAxisForward) targetRotation *= Quaternion.Euler(90, 0, 0);
return Quaternion.RotateTowards(simulatedRotation, targetRotation, maxDegrees);
}
return simulatedRotation;
}
/// <summary>\copydoc Pathfinding::IAstarAI::Move</summary>
public virtual void Move (Vector3 deltaPosition) {
accumulatedMovementDelta += deltaPosition;
}
/// <summary>
/// Moves the agent to a position.
///
/// This is used if you want to override how the agent moves. For example if you are using
/// root motion with Mecanim.
///
/// This will use a CharacterController, Rigidbody, Rigidbody2D or the Transform component depending on what options
/// are available.
///
/// The agent will be clamped to the navmesh after the movement (if such information is available, generally this is only done by the RichAI component).
///
/// See: <see cref="MovementUpdate"/> for some example code.
/// See: <see cref="controller"/>, <see cref="rigid"/>, <see cref="rigid2D"/>
/// </summary>
/// <param name="nextPosition">New position of the agent.</param>
/// <param name="nextRotation">New rotation of the agent. If #enableRotation is false then this parameter will be ignored.</param>
public virtual void FinalizeMovement (Vector3 nextPosition, Quaternion nextRotation) {
if (enableRotation) FinalizeRotation(nextRotation);
FinalizePosition(nextPosition);
}
void FinalizeRotation (Quaternion nextRotation) {
simulatedRotation = nextRotation;
if (updateRotation) {
if (rigid != null) rigid.MoveRotation(nextRotation);
else if (rigid2D != null) rigid2D.MoveRotation(nextRotation.eulerAngles.z);
else tr.rotation = nextRotation;
}
}
void FinalizePosition (Vector3 nextPosition) {
// Use a local variable, it is significantly faster
Vector3 currentPosition = simulatedPosition;
bool positionDirty1 = false;
if (controller != null && controller.enabled && updatePosition) {
// Use CharacterController
// The Transform may not be at #position if it was outside the navmesh and had to be moved to the closest valid position
tr.position = currentPosition;
controller.Move((nextPosition - currentPosition) + accumulatedMovementDelta);
// Grab the position after the movement to be able to take physics into account
// TODO: Add this into the clampedPosition calculation below to make RVO better respond to physics
currentPosition = tr.position;
if (controller.isGrounded) verticalVelocity = 0;
} else {
// Use Transform, Rigidbody, Rigidbody2D or nothing at all (if updatePosition = false)
float lastElevation;
movementPlane.ToPlane(currentPosition, out lastElevation);
currentPosition = nextPosition + accumulatedMovementDelta;
// Position the character on the ground
if (usingGravity) currentPosition = RaycastPosition(currentPosition, lastElevation);
positionDirty1 = true;
}
// Clamp the position to the navmesh after movement is done
bool positionDirty2 = false;
currentPosition = ClampToNavmesh(currentPosition, out positionDirty2);
// Assign the final position to the character if we haven't already set it (mostly for performance, setting the position can be slow)
if ((positionDirty1 || positionDirty2) && updatePosition) {
// Note that rigid.MovePosition may or may not move the character immediately.
// Check the Unity documentation for the special cases.
if (rigid != null) rigid.MovePosition(currentPosition);
else if (rigid2D != null) rigid2D.MovePosition(currentPosition);
else tr.position = currentPosition;
}
accumulatedMovementDelta = Vector3.zero;
simulatedPosition = currentPosition;
UpdateVelocity();
}
protected void UpdateVelocity () {
var currentFrame = Time.frameCount;
if (currentFrame != prevFrame) prevPosition2 = prevPosition1;
prevPosition1 = position;
prevFrame = currentFrame;
}
/// <summary>
/// Constrains the character's position to lie on the navmesh.
/// Not all movement scripts have support for this.
///
/// Returns: New position of the character that has been clamped to the navmesh.
/// </summary>
/// <param name="position">Current position of the character.</param>
/// <param name="positionChanged">True if the character's position was modified by this method.</param>
protected virtual Vector3 ClampToNavmesh (Vector3 position, out bool positionChanged) {
positionChanged = false;
return position;
}
/// <summary>
/// Checks if the character is grounded and prevents ground penetration.
///
/// Sets <see cref="verticalVelocity"/> to zero if the character is grounded.
///
/// Returns: The new position of the character.
/// </summary>
/// <param name="position">Position of the character in the world.</param>
/// <param name="lastElevation">Elevation coordinate before the agent was moved. This is along the 'up' axis of the #movementPlane.</param>
protected Vector3 RaycastPosition (Vector3 position, float lastElevation) {
RaycastHit hit;
float elevation;
movementPlane.ToPlane(position, out elevation);
float rayLength = tr.localScale.y * height * 0.5f + Mathf.Max(0, lastElevation-elevation);
Vector3 rayOffset = movementPlane.ToWorld(Vector2.zero, rayLength);
if (Physics.Raycast(position + rayOffset, -rayOffset, out hit, rayLength, groundMask, QueryTriggerInteraction.Ignore)) {
// Grounded
// Make the vertical velocity fall off exponentially. This is reasonable from a physical standpoint as characters
// are not completely stiff and touching the ground will not immediately negate all velocity downwards. The AI will
// stop moving completely due to the raycast penetration test but it will still *try* to move downwards. This helps
// significantly when moving down along slopes as if the vertical velocity would be set to zero when the character
// was grounded it would lead to a kind of 'bouncing' behavior (try it, it's hard to explain). Ideally this should
// use a more physically correct formula but this is a good approximation and is much more performant. The constant
// '5' in the expression below determines how quickly it converges but high values can lead to too much noise.
verticalVelocity *= System.Math.Max(0, 1 - 5 * lastDeltaTime);
return hit.point;
}
return position;
}
protected virtual void OnDrawGizmosSelected () {
// When selected in the Unity inspector it's nice to make the component react instantly if
// any other components are attached/detached or enabled/disabled.
// We don't want to do this normally every frame because that would be expensive.
if (Application.isPlaying) FindComponents();
}
public static readonly Color ShapeGizmoColor = new Color(240/255f, 213/255f, 30/255f);
protected virtual void OnDrawGizmos () {
if (!Application.isPlaying || !enabled) FindComponents();
var color = ShapeGizmoColor;
if (orientation == OrientationMode.YAxisForward) {
Draw.Gizmos.Cylinder(position, Vector3.forward, 0, radius * tr.localScale.x, color);
} else {
Draw.Gizmos.Cylinder(position, rotation * Vector3.up, tr.localScale.y * height, radius * tr.localScale.x, color);
}
if (!float.IsPositiveInfinity(destination.x) && Application.isPlaying) Draw.Gizmos.CircleXZ(destination, 0.2f, Color.blue);
autoRepath.DrawGizmos((IAstarAI)this);
}
protected override void Reset () {
ResetShape();
base.Reset();
}
void ResetShape () {
var cc = GetComponent<CharacterController>();
if (cc != null) {
radius = cc.radius;
height = Mathf.Max(radius*2, cc.height);
}
}
protected override int OnUpgradeSerializedData (int version, bool unityThread) {
if (unityThread && !float.IsNaN(centerOffsetCompatibility)) {
height = centerOffsetCompatibility*2;
ResetShape();
centerOffsetCompatibility = float.NaN;
}
#pragma warning disable 618
if (unityThread && targetCompatibility != null) target = targetCompatibility;
#pragma warning restore 618
if (version <= 3) {
repathRate = repathRateCompatibility;
canSearch = canSearchCompability;
}
return 5;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: a08f67bbe580e4ddfaebd06363c9cc97
timeCreated: 1496932372
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 100
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,701 @@
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Pathfinding {
using Pathfinding.Util;
/// <summary>
/// Linearly interpolating movement script.
/// This movement script will follow the path exactly, it uses linear interpolation to move between the waypoints in the path.
/// This is desirable for some types of games.
/// It also works in 2D.
///
/// See: You can see an example of this script in action in the example scene called Example15_2D.
///
/// \section rec Configuration
/// \subsection rec-snapped Recommended setup for movement along connections
///
/// This depends on what type of movement you are aiming for.
/// If you are aiming for movement where the unit follows the path exactly and move only along the graph connections on a grid/point graph.
/// I recommend that you adjust the StartEndModifier on the Seeker component: set the 'Start Point Snapping' field to 'NodeConnection' and the 'End Point Snapping' field to 'SnapToNode'.
/// [Open online documentation to see images]
/// [Open online documentation to see images]
///
/// \subsection rec-smooth Recommended setup for smooth movement
/// If you on the other hand want smoother movement I recommend setting 'Start Point Snapping' and 'End Point Snapping' to 'ClosestOnNode' and to add the Simple Smooth Modifier to the GameObject as well.
/// Alternatively you can use the <see cref="Pathfinding.FunnelModifier Funnel"/> which works better on navmesh/recast graphs or the <see cref="Pathfinding.RaycastModifier"/>.
///
/// You should not combine the Simple Smooth Modifier or the Funnel Modifier with the NodeConnection snapping mode. This may lead to very odd behavior.
///
/// [Open online documentation to see images]
/// [Open online documentation to see images]
/// You may also want to tweak the <see cref="rotationSpeed"/>.
///
/// \ingroup movementscripts
/// </summary>
[RequireComponent(typeof(Seeker))]
[AddComponentMenu("Pathfinding/AI/AILerp (2D,3D)")]
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_a_i_lerp.php")]
public class AILerp : VersionedMonoBehaviour, IAstarAI {
/// <summary>
/// Determines how often it will search for new paths.
/// If you have fast moving targets or AIs, you might want to set it to a lower value.
/// The value is in seconds between path requests.
///
/// Deprecated: This has been renamed to \reflink{autoRepath.interval}.
/// See: \reflink{AutoRepathPolicy}
/// </summary>
public float repathRate {
get {
return this.autoRepath.interval;
}
set {
this.autoRepath.interval = value;
}
}
/// <summary>
/// \copydoc Pathfinding::IAstarAI::canSearch
/// Deprecated: This has been superseded by \reflink{autoRepath.mode}.
/// </summary>
public bool canSearch {
get {
return this.autoRepath.mode != AutoRepathPolicy.Mode.Never;
}
set {
this.autoRepath.mode = value ? AutoRepathPolicy.Mode.EveryNSeconds : AutoRepathPolicy.Mode.Never;
}
}
/// <summary>
/// Determines how the agent recalculates its path automatically.
/// This corresponds to the settings under the "Recalculate Paths Automatically" field in the inspector.
/// </summary>
public AutoRepathPolicy autoRepath = new AutoRepathPolicy();
/// <summary>\copydoc Pathfinding::IAstarAI::canMove</summary>
public bool canMove = true;
/// <summary>Speed in world units</summary>
public float speed = 3;
/// <summary>
/// Determines which direction the agent moves in.
/// For 3D games you most likely want the ZAxisIsForward option as that is the convention for 3D games.
/// For 2D games you most likely want the YAxisIsForward option as that is the convention for 2D games.
///
/// Using the YAxisForward option will also allow the agent to assume that the movement will happen in the 2D (XY) plane instead of the XZ plane
/// if it does not know. This is important only for the point graph which does not have a well defined up direction. The other built-in graphs (e.g the grid graph)
/// will all tell the agent which movement plane it is supposed to use.
///
/// [Open online documentation to see images]
/// </summary>
[UnityEngine.Serialization.FormerlySerializedAs("rotationIn2D")]
public OrientationMode orientation = OrientationMode.ZAxisForward;
/// <summary>
/// If true, the forward axis of the character will be along the Y axis instead of the Z axis.
///
/// Deprecated: Use <see cref="orientation"/> instead
/// </summary>
[System.Obsolete("Use orientation instead")]
public bool rotationIn2D {
get { return orientation == OrientationMode.YAxisForward; }
set { orientation = value ? OrientationMode.YAxisForward : OrientationMode.ZAxisForward; }
}
/// <summary>
/// If true, the AI will rotate to face the movement direction.
/// See: <see cref="orientation"/>
/// </summary>
public bool enableRotation = true;
/// <summary>How quickly to rotate</summary>
public float rotationSpeed = 10;
/// <summary>
/// If true, some interpolation will be done when a new path has been calculated.
/// This is used to avoid short distance teleportation.
/// See: <see cref="switchPathInterpolationSpeed"/>
/// </summary>
public bool interpolatePathSwitches = true;
/// <summary>
/// How quickly to interpolate to the new path.
/// See: <see cref="interpolatePathSwitches"/>
/// </summary>
public float switchPathInterpolationSpeed = 5;
/// <summary>True if the end of the current path has been reached</summary>
public bool reachedEndOfPath { get; private set; }
/// <summary>\copydoc Pathfinding::IAstarAI::reachedDestination</summary>
public bool reachedDestination {
get {
if (!reachedEndOfPath || !interpolator.valid) return false;
// Note: distanceToSteeringTarget is the distance to the end of the path when approachingPathEndpoint is true
var dir = destination - interpolator.endPoint;
// Ignore either the y or z coordinate depending on if we are using 2D mode or not
if (orientation == OrientationMode.YAxisForward) dir.z = 0;
else dir.y = 0;
// Check against using a very small margin
// In theory a check against 0 should be done, but this will be a bit more resilient against targets that move slowly or maybe jitter around due to floating point errors.
if (remainingDistance + dir.magnitude >= 0.05f) return false;
return true;
}
}
public Vector3 destination { get; set; }
/// <summary>
/// Determines if the character's position should be coupled to the Transform's position.
/// If false then all movement calculations will happen as usual, but the object that this component is attached to will not move
/// instead only the <see cref="position"/> property will change.
///
/// See: <see cref="canMove"/> which in contrast to this field will disable all movement calculations.
/// See: <see cref="updateRotation"/>
/// </summary>
[System.NonSerialized]
public bool updatePosition = true;
/// <summary>
/// Determines if the character's rotation should be coupled to the Transform's rotation.
/// If false then all movement calculations will happen as usual, but the object that this component is attached to will not rotate
/// instead only the <see cref="rotation"/> property will change.
///
/// See: <see cref="updatePosition"/>
/// </summary>
[System.NonSerialized]
public bool updateRotation = true;
/// <summary>
/// Target to move towards.
/// The AI will try to follow/move towards this target.
/// It can be a point on the ground where the player has clicked in an RTS for example, or it can be the player object in a zombie game.
///
/// Deprecated: In 4.0 this will automatically add a <see cref="Pathfinding.AIDestinationSetter"/> component and set the target on that component.
/// Try instead to use the <see cref="destination"/> property which does not require a transform to be created as the target or use
/// the AIDestinationSetter component directly.
/// </summary>
[System.Obsolete("Use the destination property or the AIDestinationSetter component instead")]
public Transform target {
get {
var setter = GetComponent<AIDestinationSetter>();
return setter != null ? setter.target : null;
}
set {
targetCompatibility = null;
var setter = GetComponent<AIDestinationSetter>();
if (setter == null) setter = gameObject.AddComponent<AIDestinationSetter>();
setter.target = value;
destination = value != null ? value.position : new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::position</summary>
public Vector3 position { get { return updatePosition ? tr.position : simulatedPosition; } }
/// <summary>\copydoc Pathfinding::IAstarAI::rotation</summary>
public Quaternion rotation {
get { return updateRotation ? tr.rotation : simulatedRotation; }
set {
if (updateRotation) {
tr.rotation = value;
} else {
simulatedRotation = value;
}
}
}
#region IAstarAI implementation
/// <summary>\copydoc Pathfinding::IAstarAI::Move</summary>
void IAstarAI.Move (Vector3 deltaPosition) {
// This script does not know the concept of being away from the path that it is following
// so this call will be ignored (as is also mentioned in the documentation).
}
/// <summary>\copydoc Pathfinding::IAstarAI::radius</summary>
float IAstarAI.radius { get { return 0; } set {} }
/// <summary>\copydoc Pathfinding::IAstarAI::height</summary>
float IAstarAI.height { get { return 0; } set {} }
/// <summary>\copydoc Pathfinding::IAstarAI::maxSpeed</summary>
float IAstarAI.maxSpeed { get { return speed; } set { speed = value; } }
/// <summary>\copydoc Pathfinding::IAstarAI::canSearch</summary>
bool IAstarAI.canSearch { get { return canSearch; } set { canSearch = value; } }
/// <summary>\copydoc Pathfinding::IAstarAI::canMove</summary>
bool IAstarAI.canMove { get { return canMove; } set { canMove = value; } }
/// <summary>\copydoc Pathfinding::IAstarAI::velocity</summary>
public Vector3 velocity {
get {
return Time.deltaTime > 0.00001f ? (previousPosition1 - previousPosition2) / Time.deltaTime : Vector3.zero;
}
}
Vector3 IAstarAI.desiredVelocity {
get {
// The AILerp script sets the position every frame. It does not take into account physics
// or other things. So the velocity should always be the same as the desired velocity.
return (this as IAstarAI).velocity;
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::steeringTarget</summary>
Vector3 IAstarAI.steeringTarget {
get {
// AILerp doesn't use steering at all, so we will just return a point ahead of the agent in the direction it is moving.
return interpolator.valid ? interpolator.position + interpolator.tangent : simulatedPosition;
}
}
#endregion
/// <summary>\copydoc Pathfinding::IAstarAI::remainingDistance</summary>
public float remainingDistance {
get {
return Mathf.Max(interpolator.remainingDistance, 0);
}
set {
interpolator.remainingDistance = Mathf.Max(value, 0);
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::hasPath</summary>
public bool hasPath {
get {
return interpolator.valid;
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::pathPending</summary>
public bool pathPending {
get {
return !canSearchAgain;
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::isStopped</summary>
public bool isStopped { get; set; }
/// <summary>\copydoc Pathfinding::IAstarAI::onSearchPath</summary>
public System.Action onSearchPath { get; set; }
/// <summary>Cached Seeker component</summary>
protected Seeker seeker;
/// <summary>Cached Transform component</summary>
protected Transform tr;
/// <summary>Current path which is followed</summary>
protected ABPath path;
/// <summary>Only when the previous path has been returned should a search for a new path be done</summary>
protected bool canSearchAgain = true;
/// <summary>
/// When a new path was returned, the AI was moving along this ray.
/// Used to smoothly interpolate between the previous movement and the movement along the new path.
/// The speed is equal to movement direction.
/// </summary>
protected Vector3 previousMovementOrigin;
protected Vector3 previousMovementDirection;
/// <summary>
/// Time since the path was replaced by a new path.
/// See: <see cref="interpolatePathSwitches"/>
/// </summary>
protected float pathSwitchInterpolationTime = 0;
protected PathInterpolator interpolator = new PathInterpolator();
/// <summary>
/// Holds if the Start function has been run.
/// Used to test if coroutines should be started in OnEnable to prevent calculating paths
/// in the awake stage (or rather before start on frame 0).
/// </summary>
bool startHasRun = false;
Vector3 previousPosition1, previousPosition2, simulatedPosition;
Quaternion simulatedRotation;
/// <summary>Required for serialization backward compatibility</summary>
[UnityEngine.Serialization.FormerlySerializedAs("target")][SerializeField][HideInInspector]
Transform targetCompatibility;
[SerializeField]
[HideInInspector]
[UnityEngine.Serialization.FormerlySerializedAs("repathRate")]
float repathRateCompatibility = float.NaN;
[SerializeField]
[HideInInspector]
[UnityEngine.Serialization.FormerlySerializedAs("canSearch")]
bool canSearchCompability = false;
protected AILerp () {
// Note that this needs to be set here in the constructor and not in e.g Awake
// because it is possible that other code runs and sets the destination property
// before the Awake method on this script runs.
destination = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
}
/// <summary>
/// Initializes reference variables.
/// If you override this function you should in most cases call base.Awake () at the start of it.
/// </summary>
protected override void Awake () {
base.Awake();
//This is a simple optimization, cache the transform component lookup
tr = transform;
seeker = GetComponent<Seeker>();
// Tell the StartEndModifier to ask for our exact position when post processing the path This
// is important if we are using prediction and requesting a path from some point slightly ahead
// of us since then the start point in the path request may be far from our position when the
// path has been calculated. This is also good because if a long path is requested, it may take
// a few frames for it to be calculated so we could have moved some distance during that time
seeker.startEndModifier.adjustStartPoint = () => simulatedPosition;
}
/// <summary>
/// Starts searching for paths.
/// If you override this function you should in most cases call base.Start () at the start of it.
/// See: <see cref="Init"/>
/// See: <see cref="RepeatTrySearchPath"/>
/// </summary>
protected virtual void Start () {
startHasRun = true;
Init();
}
/// <summary>Called when the component is enabled</summary>
protected virtual void OnEnable () {
// Make sure we receive callbacks when paths complete
seeker.pathCallback += OnPathComplete;
Init();
}
void Init () {
if (startHasRun) {
// The Teleport call will make sure some variables are properly initialized (like #prevPosition1 and #prevPosition2)
Teleport(position, false);
autoRepath.Reset();
if (shouldRecalculatePath) SearchPath();
}
}
public void OnDisable () {
ClearPath();
// Make sure we no longer receive callbacks when paths complete
seeker.pathCallback -= OnPathComplete;
}
/// <summary>\copydoc Pathfinding::IAstarAI::GetRemainingPath</summary>
public void GetRemainingPath (List<Vector3> buffer, out bool stale) {
buffer.Clear();
if (!interpolator.valid) {
buffer.Add(position);
stale = true;
return;
}
stale = false;
interpolator.GetRemainingPath(buffer);
// The agent is almost always at interpolation.position (which is buffer[0])
// but sometimes - in particular when interpolating between two paths - the agent might at a slightly different position.
// So we replace the first point with the actual position of the agent.
buffer[0] = position;
}
public void Teleport (Vector3 position, bool clearPath = true) {
if (clearPath) ClearPath();
simulatedPosition = previousPosition1 = previousPosition2 = position;
if (updatePosition) tr.position = position;
reachedEndOfPath = false;
if (clearPath) SearchPath();
}
/// <summary>True if the path should be automatically recalculated as soon as possible</summary>
protected virtual bool shouldRecalculatePath {
get {
return canSearchAgain && autoRepath.ShouldRecalculatePath((IAstarAI)this);
}
}
/// <summary>
/// Requests a path to the target.
/// Deprecated: Use <see cref="SearchPath"/> instead.
/// </summary>
[System.Obsolete("Use SearchPath instead")]
public virtual void ForceSearchPath () {
SearchPath();
}
/// <summary>Requests a path to the target.</summary>
public virtual void SearchPath () {
if (float.IsPositiveInfinity(destination.x)) return;
if (onSearchPath != null) onSearchPath();
// This is where the path should start to search from
var currentPosition = GetFeetPosition();
// If we are following a path, start searching from the node we will
// reach next this can prevent odd turns right at the start of the path
/*if (interpolator.valid) {
var prevDist = interpolator.distance;
// Move to the end of the current segment
interpolator.MoveToSegment(interpolator.segmentIndex, 1);
currentPosition = interpolator.position;
// Move back to the original position
interpolator.distance = prevDist;
}*/
canSearchAgain = false;
// Create a new path request
// The OnPathComplete method will later be called with the result
SetPath(ABPath.Construct(currentPosition, destination, null));
}
/// <summary>
/// The end of the path has been reached.
/// If you want custom logic for when the AI has reached it's destination
/// add it here.
/// You can also create a new script which inherits from this one
/// and override the function in that script.
/// </summary>
public virtual void OnTargetReached () {
}
/// <summary>
/// Called when a requested path has finished calculation.
/// A path is first requested by <see cref="SearchPath"/>, it is then calculated, probably in the same or the next frame.
/// Finally it is returned to the seeker which forwards it to this function.
/// </summary>
protected virtual void OnPathComplete (Path _p) {
ABPath p = _p as ABPath;
if (p == null) throw new System.Exception("This function only handles ABPaths, do not use special path types");
canSearchAgain = true;
// Increase the reference count on the path.
// This is used for path pooling
p.Claim(this);
// Path couldn't be calculated of some reason.
// More info in p.errorLog (debug string)
if (p.error) {
p.Release(this);
return;
}
if (interpolatePathSwitches) {
ConfigurePathSwitchInterpolation();
}
// Replace the old path
var oldPath = path;
path = p;
reachedEndOfPath = false;
// Just for the rest of the code to work, if there
// is only one waypoint in the path add another one
if (path.vectorPath != null && path.vectorPath.Count == 1) {
path.vectorPath.Insert(0, GetFeetPosition());
}
// Reset some variables
ConfigureNewPath();
// Release the previous path
// This is used for path pooling.
// This is done after the interpolator has been configured in the ConfigureNewPath method
// as this method would otherwise invalidate the interpolator
// since the vectorPath list (which the interpolator uses) will be pooled.
if (oldPath != null) oldPath.Release(this);
if (interpolator.remainingDistance < 0.0001f && !reachedEndOfPath) {
reachedEndOfPath = true;
OnTargetReached();
}
}
/// <summary>
/// Clears the current path of the agent.
///
/// Usually invoked using <see cref="SetPath(null)"/>
///
/// See: <see cref="SetPath"/>
/// See: <see cref="isStopped"/>
/// </summary>
protected virtual void ClearPath () {
// Abort any calculations in progress
if (seeker != null) seeker.CancelCurrentPathRequest();
canSearchAgain = true;
reachedEndOfPath = false;
// Release current path so that it can be pooled
if (path != null) path.Release(this);
path = null;
interpolator.SetPath(null);
}
/// <summary>\copydoc Pathfinding::IAstarAI::SetPath</summary>
public void SetPath (Path path) {
if (path == null) {
ClearPath();
} else if (path.PipelineState == PathState.Created) {
// Path has not started calculation yet
canSearchAgain = false;
seeker.CancelCurrentPathRequest();
seeker.StartPath(path);
autoRepath.DidRecalculatePath(destination);
} else if (path.PipelineState == PathState.Returned) {
// Path has already been calculated
// We might be calculating another path at the same time, and we don't want that path to override this one. So cancel it.
if (seeker.GetCurrentPath() != path) seeker.CancelCurrentPathRequest();
else throw new System.ArgumentException("If you calculate the path using seeker.StartPath then this script will pick up the calculated path anyway as it listens for all paths the Seeker finishes calculating. You should not call SetPath in that case.");
OnPathComplete(path);
} else {
// Path calculation has been started, but it is not yet complete. Cannot really handle this.
throw new System.ArgumentException("You must call the SetPath method with a path that either has been completely calculated or one whose path calculation has not been started at all. It looks like the path calculation for the path you tried to use has been started, but is not yet finished.");
}
}
protected virtual void ConfigurePathSwitchInterpolation () {
bool reachedEndOfPreviousPath = interpolator.valid && interpolator.remainingDistance < 0.0001f;
if (interpolator.valid && !reachedEndOfPreviousPath) {
previousMovementOrigin = interpolator.position;
previousMovementDirection = interpolator.tangent.normalized * interpolator.remainingDistance;
pathSwitchInterpolationTime = 0;
} else {
previousMovementOrigin = Vector3.zero;
previousMovementDirection = Vector3.zero;
pathSwitchInterpolationTime = float.PositiveInfinity;
}
}
public virtual Vector3 GetFeetPosition () {
return position;
}
/// <summary>Finds the closest point on the current path and configures the <see cref="interpolator"/></summary>
protected virtual void ConfigureNewPath () {
var hadValidPath = interpolator.valid;
var prevTangent = hadValidPath ? interpolator.tangent : Vector3.zero;
interpolator.SetPath(path.vectorPath);
interpolator.MoveToClosestPoint(GetFeetPosition());
if (interpolatePathSwitches && switchPathInterpolationSpeed > 0.01f && hadValidPath) {
var correctionFactor = Mathf.Max(-Vector3.Dot(prevTangent.normalized, interpolator.tangent.normalized), 0);
interpolator.distance -= speed*correctionFactor*(1f/switchPathInterpolationSpeed);
}
}
protected virtual void Update () {
if (shouldRecalculatePath) SearchPath();
if (canMove) {
Vector3 nextPosition;
Quaternion nextRotation;
MovementUpdate(Time.deltaTime, out nextPosition, out nextRotation);
FinalizeMovement(nextPosition, nextRotation);
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::MovementUpdate</summary>
public void MovementUpdate (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) {
if (updatePosition) simulatedPosition = tr.position;
if (updateRotation) simulatedRotation = tr.rotation;
Vector3 direction;
nextPosition = CalculateNextPosition(out direction, isStopped ? 0f : deltaTime);
if (enableRotation) nextRotation = SimulateRotationTowards(direction, deltaTime);
else nextRotation = simulatedRotation;
}
/// <summary>\copydoc Pathfinding::IAstarAI::FinalizeMovement</summary>
public void FinalizeMovement (Vector3 nextPosition, Quaternion nextRotation) {
previousPosition2 = previousPosition1;
previousPosition1 = simulatedPosition = nextPosition;
simulatedRotation = nextRotation;
if (updatePosition) tr.position = nextPosition;
if (updateRotation) tr.rotation = nextRotation;
}
Quaternion SimulateRotationTowards (Vector3 direction, float deltaTime) {
// Rotate unless we are really close to the target
if (direction != Vector3.zero) {
Quaternion targetRotation = Quaternion.LookRotation(direction, orientation == OrientationMode.YAxisForward ? Vector3.back : Vector3.up);
// This causes the character to only rotate around the Z axis
if (orientation == OrientationMode.YAxisForward) targetRotation *= Quaternion.Euler(90, 0, 0);
return Quaternion.Slerp(simulatedRotation, targetRotation, deltaTime * rotationSpeed);
}
return simulatedRotation;
}
/// <summary>Calculate the AI's next position (one frame in the future).</summary>
/// <param name="direction">The tangent of the segment the AI is currently traversing. Not normalized.</param>
protected virtual Vector3 CalculateNextPosition (out Vector3 direction, float deltaTime) {
if (!interpolator.valid) {
direction = Vector3.zero;
return simulatedPosition;
}
interpolator.distance += deltaTime * speed;
if (interpolator.remainingDistance < 0.0001f && !reachedEndOfPath) {
reachedEndOfPath = true;
OnTargetReached();
}
direction = interpolator.tangent;
pathSwitchInterpolationTime += deltaTime;
var alpha = switchPathInterpolationSpeed * pathSwitchInterpolationTime;
if (interpolatePathSwitches && alpha < 1f) {
// Find the approximate position we would be at if we
// would have continued to follow the previous path
Vector3 positionAlongPreviousPath = previousMovementOrigin + Vector3.ClampMagnitude(previousMovementDirection, speed * pathSwitchInterpolationTime);
// Interpolate between the position on the current path and the position
// we would have had if we would have continued along the previous path.
return Vector3.Lerp(positionAlongPreviousPath, interpolator.position, alpha);
} else {
return interpolator.position;
}
}
protected override int OnUpgradeSerializedData (int version, bool unityThread) {
#pragma warning disable 618
if (unityThread && targetCompatibility != null) target = targetCompatibility;
#pragma warning restore 618
if (version <= 3) {
repathRate = repathRateCompatibility;
canSearch = canSearchCompability;
}
return 4;
}
public virtual void OnDrawGizmos () {
tr = transform;
autoRepath.DrawGizmos((IAstarAI)this);
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 847a14d4dc9cc43679ab34fc78e0182f
timeCreated: 1454879612
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,491 @@
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Pathfinding {
using Pathfinding.RVO;
using Pathfinding.Util;
/// <summary>
/// AI for following paths.
/// This AI is the default movement script which comes with the A* Pathfinding Project.
/// It is in no way required by the rest of the system, so feel free to write your own. But I hope this script will make it easier
/// to set up movement for the characters in your game.
/// This script works well for many types of units, but if you need the highest performance (for example if you are moving hundreds of characters) you
/// may want to customize this script or write a custom movement script to be able to optimize it specifically for your game.
///
/// This script will try to move to a given <see cref="destination"/>. At <see cref="repathRate regular"/>, the path to the destination will be recalculated.
/// If you want to make the AI to follow a particular object you can attach the <see cref="Pathfinding.AIDestinationSetter"/> component.
/// Take a look at the getstarted (view in online documentation for working links) tutorial for more instructions on how to configure this script.
///
/// Here is a video of this script being used move an agent around (technically it uses the <see cref="Pathfinding.Examples.MineBotAI"/> script that inherits from this one but adds a bit of animation support for the example scenes):
/// [Open online documentation to see videos]
///
/// \section variables Quick overview of the variables
/// In the inspector in Unity, you will see a bunch of variables. You can view detailed information further down, but here's a quick overview.
///
/// The <see cref="repathRate"/> determines how often it will search for new paths, if you have fast moving targets, you might want to set it to a lower value.
/// The <see cref="destination"/> field is where the AI will try to move, it can be a point on the ground where the player has clicked in an RTS for example.
/// Or it can be the player object in a zombie game.
/// The <see cref="maxSpeed"/> is self-explanatory, as is <see cref="rotationSpeed"/>. however <see cref="slowdownDistance"/> might require some explanation:
/// It is the approximate distance from the target where the AI will start to slow down. Setting it to a large value will make the AI slow down very gradually.
/// <see cref="pickNextWaypointDist"/> determines the distance to the point the AI will move to (see image below).
///
/// Below is an image illustrating several variables that are exposed by this class (<see cref="pickNextWaypointDist"/>, <see cref="steeringTarget"/>, <see cref="desiredVelocity)"/>
/// [Open online documentation to see images]
///
/// This script has many movement fallbacks.
/// If it finds an RVOController attached to the same GameObject as this component, it will use that. If it finds a character controller it will also use that.
/// If it finds a rigidbody it will use that. Lastly it will fall back to simply modifying Transform.position which is guaranteed to always work and is also the most performant option.
///
/// \section how-aipath-works How it works
/// In this section I'm going to go over how this script is structured and how information flows.
/// This is useful if you want to make changes to this script or if you just want to understand how it works a bit more deeply.
/// However you do not need to read this section if you are just going to use the script as-is.
///
/// This script inherits from the <see cref="AIBase"/> class. The movement happens either in Unity's standard <see cref="Update"/> or <see cref="FixedUpdate"/> method.
/// They are both defined in the AIBase class. Which one is actually used depends on if a rigidbody is used for movement or not.
/// Rigidbody movement has to be done inside the FixedUpdate method while otherwise it is better to do it in Update.
///
/// From there a call is made to the <see cref="MovementUpdate"/> method (which in turn calls <see cref="MovementUpdateInternal)"/>.
/// This method contains the main bulk of the code and calculates how the AI *wants* to move. However it doesn't do any movement itself.
/// Instead it returns the position and rotation it wants the AI to move to have at the end of the frame.
/// The <see cref="Update"/> (or <see cref="FixedUpdate)"/> method then passes these values to the <see cref="FinalizeMovement"/> method which is responsible for actually moving the character.
/// That method also handles things like making sure the AI doesn't fall through the ground using raycasting.
///
/// The AI recalculates its path regularly. This happens in the Update method which checks <see cref="shouldRecalculatePath"/> and if that returns true it will call <see cref="SearchPath"/>.
/// The <see cref="SearchPath"/> method will prepare a path request and send it to the <see cref="Pathfinding.Seeker"/> component which should be attached to the same GameObject as this script.
/// Since this script will when waking up register to the <see cref="Pathfinding.Seeker.pathCallback"/> delegate this script will be notified every time a new path is calculated by the <see cref="OnPathComplete"/> method being called.
/// It may take one or sometimes multiple frames for the path to be calculated, but finally the <see cref="OnPathComplete"/> method will be called and the current path that the AI is following will be replaced.
/// </summary>
[AddComponentMenu("Pathfinding/AI/AIPath (2D,3D)")]
public partial class AIPath : AIBase, IAstarAI {
/// <summary>
/// How quickly the agent accelerates.
/// Positive values represent an acceleration in world units per second squared.
/// Negative values are interpreted as an inverse time of how long it should take for the agent to reach its max speed.
/// For example if it should take roughly 0.4 seconds for the agent to reach its max speed then this field should be set to -1/0.4 = -2.5.
/// For a negative value the final acceleration will be: -acceleration*maxSpeed.
/// This behaviour exists mostly for compatibility reasons.
///
/// In the Unity inspector there are two modes: Default and Custom. In the Default mode this field is set to -2.5 which means that it takes about 0.4 seconds for the agent to reach its top speed.
/// In the Custom mode you can set the acceleration to any positive value.
/// </summary>
public float maxAcceleration = -2.5f;
/// <summary>
/// Rotation speed in degrees per second.
/// Rotation is calculated using Quaternion.RotateTowards. This variable represents the rotation speed in degrees per second.
/// The higher it is, the faster the character will be able to rotate.
/// </summary>
[UnityEngine.Serialization.FormerlySerializedAs("turningSpeed")]
public float rotationSpeed = 360;
/// <summary>Distance from the end of the path where the AI will start to slow down</summary>
public float slowdownDistance = 0.6F;
/// <summary>
/// How far the AI looks ahead along the path to determine the point it moves to.
/// In world units.
/// If you enable the <see cref="alwaysDrawGizmos"/> toggle this value will be visualized in the scene view as a blue circle around the agent.
/// [Open online documentation to see images]
///
/// Here are a few example videos showing some typical outcomes with good values as well as how it looks when this value is too low and too high.
/// <table>
/// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-danger">Too low</span><br/></verbatim>\endxmlonly A too low value and a too low acceleration will result in the agent overshooting a lot and not managing to follow the path well.</td></tr>
/// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-warning">Ok</span><br/></verbatim>\endxmlonly A low value but a high acceleration works decently to make the AI follow the path more closely. Note that the <see cref="Pathfinding.AILerp"/> component is better suited if you want the agent to follow the path without any deviations.</td></tr>
/// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-success">Ok</span><br/></verbatim>\endxmlonly A reasonable value in this example.</td></tr>
/// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-success">Ok</span><br/></verbatim>\endxmlonly A reasonable value in this example, but the path is followed slightly more loosely than in the previous video.</td></tr>
/// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-danger">Too high</span><br/></verbatim>\endxmlonly A too high value will make the agent follow the path too loosely and may cause it to try to move through obstacles.</td></tr>
/// </table>
/// </summary>
public float pickNextWaypointDist = 2;
/// <summary>
/// Distance to the end point to consider the end of path to be reached.
/// When the end is within this distance then <see cref="OnTargetReached"/> will be called and <see cref="reachedEndOfPath"/> will return true.
/// </summary>
public float endReachedDistance = 0.2F;
/// <summary>Draws detailed gizmos constantly in the scene view instead of only when the agent is selected and settings are being modified</summary>
public bool alwaysDrawGizmos;
/// <summary>
/// Slow down when not facing the target direction.
/// Incurs at a small performance overhead.
/// </summary>
public bool slowWhenNotFacingTarget = true;
/// <summary>
/// What to do when within <see cref="endReachedDistance"/> units from the destination.
/// The character can either stop immediately when it comes within that distance, which is useful for e.g archers
/// or other ranged units that want to fire on a target. Or the character can continue to try to reach the exact
/// destination point and come to a full stop there. This is useful if you want the character to reach the exact
/// point that you specified.
///
/// Note: <see cref="reachedEndOfPath"/> will become true when the character is within <see cref="endReachedDistance"/> units from the destination
/// regardless of what this field is set to.
/// </summary>
public CloseToDestinationMode whenCloseToDestination = CloseToDestinationMode.Stop;
/// <summary>
/// Ensure that the character is always on the traversable surface of the navmesh.
/// When this option is enabled a <see cref="AstarPath.GetNearest"/> query will be done every frame to find the closest node that the agent can walk on
/// and if the agent is not inside that node, then the agent will be moved to it.
///
/// This is especially useful together with local avoidance in order to avoid agents pushing each other into walls.
/// See: local-avoidance (view in online documentation for working links) for more info about this.
///
/// This option also integrates with local avoidance so that if the agent is say forced into a wall by other agents the local avoidance
/// system will be informed about that wall and can take that into account.
///
/// Enabling this has some performance impact depending on the graph type (pretty fast for grid graphs, slightly slower for navmesh/recast graphs).
/// If you are using a navmesh/recast graph you may want to switch to the <see cref="Pathfinding.RichAI"/> movement script which is specifically written for navmesh/recast graphs and
/// does this kind of clamping out of the box. In many cases it can also follow the path more smoothly around sharp bends in the path.
///
/// It is not recommended that you use this option together with the funnel modifier on grid graphs because the funnel modifier will make the path
/// go very close to the border of the graph and this script has a tendency to try to cut corners a bit. This may cause it to try to go slightly outside the
/// traversable surface near corners and that will look bad if this option is enabled.
///
/// Warning: This option makes no sense to use on point graphs because point graphs do not have a surface.
/// Enabling this option when using a point graph will lead to the agent being snapped to the closest node every frame which is likely not what you want.
///
/// Below you can see an image where several agents using local avoidance were ordered to go to the same point in a corner.
/// When not constraining the agents to the graph they are easily pushed inside obstacles.
/// [Open online documentation to see images]
/// </summary>
public bool constrainInsideGraph = false;
/// <summary>Current path which is followed</summary>
protected Path path;
/// <summary>Helper which calculates points along the current path</summary>
protected PathInterpolator interpolator = new PathInterpolator();
#region IAstarAI implementation
/// <summary>\copydoc Pathfinding::IAstarAI::Teleport</summary>
public override void Teleport (Vector3 newPosition, bool clearPath = true) {
reachedEndOfPath = false;
base.Teleport(newPosition, clearPath);
}
/// <summary>\copydoc Pathfinding::IAstarAI::remainingDistance</summary>
public float remainingDistance {
get {
return interpolator.valid ? interpolator.remainingDistance + movementPlane.ToPlane(interpolator.position - position).magnitude : float.PositiveInfinity;
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::reachedDestination</summary>
public bool reachedDestination {
get {
if (!reachedEndOfPath) return false;
if (!interpolator.valid || remainingDistance + movementPlane.ToPlane(destination - interpolator.endPoint).magnitude > endReachedDistance) return false;
// Don't do height checks in 2D mode
if (orientation != OrientationMode.YAxisForward) {
// Check if the destination is above the head of the character or far below the feet of it
float yDifference;
movementPlane.ToPlane(destination - position, out yDifference);
var h = tr.localScale.y * height;
if (yDifference > h || yDifference < -h*0.5) return false;
}
return true;
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::reachedEndOfPath</summary>
public bool reachedEndOfPath { get; protected set; }
/// <summary>\copydoc Pathfinding::IAstarAI::hasPath</summary>
public bool hasPath {
get {
return interpolator.valid;
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::pathPending</summary>
public bool pathPending {
get {
return waitingForPathCalculation;
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::steeringTarget</summary>
public Vector3 steeringTarget {
get {
return interpolator.valid ? interpolator.position : position;
}
}
/// <summary>\copydoc Pathfinding::IAstarAI::radius</summary>
float IAstarAI.radius { get { return radius; } set { radius = value; } }
/// <summary>\copydoc Pathfinding::IAstarAI::height</summary>
float IAstarAI.height { get { return height; } set { height = value; } }
/// <summary>\copydoc Pathfinding::IAstarAI::maxSpeed</summary>
float IAstarAI.maxSpeed { get { return maxSpeed; } set { maxSpeed = value; } }
/// <summary>\copydoc Pathfinding::IAstarAI::canSearch</summary>
bool IAstarAI.canSearch { get { return canSearch; } set { canSearch = value; } }
/// <summary>\copydoc Pathfinding::IAstarAI::canMove</summary>
bool IAstarAI.canMove { get { return canMove; } set { canMove = value; } }
#endregion
/// <summary>\copydoc Pathfinding::IAstarAI::GetRemainingPath</summary>
public void GetRemainingPath (List<Vector3> buffer, out bool stale) {
buffer.Clear();
buffer.Add(position);
if (!interpolator.valid) {
stale = true;
return;
}
stale = false;
interpolator.GetRemainingPath(buffer);
}
protected override void OnDisable () {
base.OnDisable();
// Release current path so that it can be pooled
if (path != null) path.Release(this);
path = null;
interpolator.SetPath(null);
reachedEndOfPath = false;
}
/// <summary>
/// The end of the path has been reached.
/// If you want custom logic for when the AI has reached it's destination add it here. You can
/// also create a new script which inherits from this one and override the function in that script.
///
/// This method will be called again if a new path is calculated as the destination may have changed.
/// So when the agent is close to the destination this method will typically be called every <see cref="repathRate"/> seconds.
/// </summary>
public virtual void OnTargetReached () {
}
/// <summary>
/// Called when a requested path has been calculated.
/// A path is first requested by <see cref="UpdatePath"/>, it is then calculated, probably in the same or the next frame.
/// Finally it is returned to the seeker which forwards it to this function.
/// </summary>
protected override void OnPathComplete (Path newPath) {
ABPath p = newPath as ABPath;
if (p == null) throw new System.Exception("This function only handles ABPaths, do not use special path types");
waitingForPathCalculation = false;
// Increase the reference count on the new path.
// This is used for object pooling to reduce allocations.
p.Claim(this);
// Path couldn't be calculated of some reason.
// More info in p.errorLog (debug string)
if (p.error) {
p.Release(this);
SetPath(null);
return;
}
// Release the previous path.
if (path != null) path.Release(this);
// Replace the old path
path = p;
// Make sure the path contains at least 2 points
if (path.vectorPath.Count == 1) path.vectorPath.Add(path.vectorPath[0]);
interpolator.SetPath(path.vectorPath);
var graph = path.path.Count > 0 ? AstarData.GetGraph(path.path[0]) as ITransformedGraph : null;
movementPlane = graph != null ? graph.transform : (orientation == OrientationMode.YAxisForward ? new GraphTransform(Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(-90, 270, 90), Vector3.one)) : GraphTransform.identityTransform);
// Reset some variables
reachedEndOfPath = false;
// Simulate movement from the point where the path was requested
// to where we are right now. This reduces the risk that the agent
// gets confused because the first point in the path is far away
// from the current position (possibly behind it which could cause
// the agent to turn around, and that looks pretty bad).
interpolator.MoveToLocallyClosestPoint((GetFeetPosition() + p.originalStartPoint) * 0.5f);
interpolator.MoveToLocallyClosestPoint(GetFeetPosition());
// Update which point we are moving towards.
// Note that we need to do this here because otherwise the remainingDistance field might be incorrect for 1 frame.
// (due to interpolator.remainingDistance being incorrect).
interpolator.MoveToCircleIntersection2D(position, pickNextWaypointDist, movementPlane);
var distanceToEnd = remainingDistance;
if (distanceToEnd <= endReachedDistance) {
reachedEndOfPath = true;
OnTargetReached();
}
}
protected override void ClearPath () {
CancelCurrentPathRequest();
if (path != null) path.Release(this);
path = null;
interpolator.SetPath(null);
reachedEndOfPath = false;
}
/// <summary>Called during either Update or FixedUpdate depending on if rigidbodies are used for movement or not</summary>
protected override void MovementUpdateInternal (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) {
float currentAcceleration = maxAcceleration;
// If negative, calculate the acceleration from the max speed
if (currentAcceleration < 0) currentAcceleration *= -maxSpeed;
if (updatePosition) {
// Get our current position. We read from transform.position as few times as possible as it is relatively slow
// (at least compared to a local variable)
simulatedPosition = tr.position;
}
if (updateRotation) simulatedRotation = tr.rotation;
var currentPosition = simulatedPosition;
// Update which point we are moving towards
interpolator.MoveToCircleIntersection2D(currentPosition, pickNextWaypointDist, movementPlane);
var dir = movementPlane.ToPlane(steeringTarget - currentPosition);
// Calculate the distance to the end of the path
float distanceToEnd = dir.magnitude + Mathf.Max(0, interpolator.remainingDistance);
// Check if we have reached the target
var prevTargetReached = reachedEndOfPath;
reachedEndOfPath = distanceToEnd <= endReachedDistance && interpolator.valid;
if (!prevTargetReached && reachedEndOfPath) OnTargetReached();
float slowdown;
// Normalized direction of where the agent is looking
var forwards = movementPlane.ToPlane(simulatedRotation * (orientation == OrientationMode.YAxisForward ? Vector3.up : Vector3.forward));
// Check if we have a valid path to follow and some other script has not stopped the character
bool stopped = isStopped || (reachedDestination && whenCloseToDestination == CloseToDestinationMode.Stop);
if (interpolator.valid && !stopped) {
// How fast to move depending on the distance to the destination.
// Move slower as the character gets closer to the destination.
// This is always a value between 0 and 1.
slowdown = distanceToEnd < slowdownDistance? Mathf.Sqrt(distanceToEnd / slowdownDistance) : 1;
if (reachedEndOfPath && whenCloseToDestination == CloseToDestinationMode.Stop) {
// Slow down as quickly as possible
velocity2D -= Vector2.ClampMagnitude(velocity2D, currentAcceleration * deltaTime);
} else {
velocity2D += MovementUtilities.CalculateAccelerationToReachPoint(dir, dir.normalized*maxSpeed, velocity2D, currentAcceleration, rotationSpeed, maxSpeed, forwards) * deltaTime;
}
} else {
slowdown = 1;
// Slow down as quickly as possible
velocity2D -= Vector2.ClampMagnitude(velocity2D, currentAcceleration * deltaTime);
}
velocity2D = MovementUtilities.ClampVelocity(velocity2D, maxSpeed, slowdown, slowWhenNotFacingTarget && enableRotation, forwards);
ApplyGravity(deltaTime);
// Set how much the agent wants to move during this frame
var delta2D = lastDeltaPosition = CalculateDeltaToMoveThisFrame(movementPlane.ToPlane(currentPosition), distanceToEnd, deltaTime);
nextPosition = currentPosition + movementPlane.ToWorld(delta2D, verticalVelocity * lastDeltaTime);
CalculateNextRotation(slowdown, out nextRotation);
}
protected virtual void CalculateNextRotation (float slowdown, out Quaternion nextRotation) {
if (lastDeltaTime > 0.00001f && enableRotation) {
Vector2 desiredRotationDirection;
desiredRotationDirection = velocity2D;
// Rotate towards the direction we are moving in.
// Don't rotate when we are very close to the target.
var currentRotationSpeed = rotationSpeed * Mathf.Max(0, (slowdown - 0.3f) / 0.7f);
nextRotation = SimulateRotationTowards(desiredRotationDirection, currentRotationSpeed * lastDeltaTime);
} else {
// TODO: simulatedRotation
nextRotation = rotation;
}
}
static NNConstraint cachedNNConstraint = NNConstraint.Default;
protected override Vector3 ClampToNavmesh (Vector3 position, out bool positionChanged) {
if (constrainInsideGraph) {
cachedNNConstraint.tags = seeker.traversableTags;
cachedNNConstraint.graphMask = seeker.graphMask;
cachedNNConstraint.distanceXZ = true;
var clampedPosition = AstarPath.active.GetNearest(position, cachedNNConstraint).position;
// We cannot simply check for equality because some precision may be lost
// if any coordinate transformations are used.
var difference = movementPlane.ToPlane(clampedPosition - position);
float sqrDifference = difference.sqrMagnitude;
if (sqrDifference > 0.001f*0.001f) {
// The agent was outside the navmesh. Remove that component of the velocity
// so that the velocity only goes along the direction of the wall, not into it
velocity2D -= difference * Vector2.Dot(difference, velocity2D) / sqrDifference;
positionChanged = true;
// Return the new position, but ignore any changes in the y coordinate from the ClampToNavmesh method as the y coordinates in the navmesh are rarely very accurate
return position + movementPlane.ToWorld(difference);
}
}
positionChanged = false;
return position;
}
#if UNITY_EDITOR
[System.NonSerialized]
int gizmoHash = 0;
[System.NonSerialized]
float lastChangedTime = float.NegativeInfinity;
protected static readonly Color GizmoColor = new Color(46.0f/255, 104.0f/255, 201.0f/255);
protected override void OnDrawGizmos () {
base.OnDrawGizmos();
if (alwaysDrawGizmos) OnDrawGizmosInternal();
}
protected override void OnDrawGizmosSelected () {
base.OnDrawGizmosSelected();
if (!alwaysDrawGizmos) OnDrawGizmosInternal();
}
void OnDrawGizmosInternal () {
var newGizmoHash = pickNextWaypointDist.GetHashCode() ^ slowdownDistance.GetHashCode() ^ endReachedDistance.GetHashCode();
if (newGizmoHash != gizmoHash && gizmoHash != 0) lastChangedTime = Time.realtimeSinceStartup;
gizmoHash = newGizmoHash;
float alpha = alwaysDrawGizmos ? 1 : Mathf.SmoothStep(1, 0, (Time.realtimeSinceStartup - lastChangedTime - 5f)/0.5f) * (UnityEditor.Selection.gameObjects.Length == 1 ? 1 : 0);
if (alpha > 0) {
// Make sure the scene view is repainted while the gizmos are visible
if (!alwaysDrawGizmos) UnityEditor.SceneView.RepaintAll();
Draw.Gizmos.Line(position, steeringTarget, GizmoColor * new Color(1, 1, 1, alpha));
Gizmos.matrix = Matrix4x4.TRS(position, transform.rotation * (orientation == OrientationMode.YAxisForward ? Quaternion.Euler(-90, 0, 0) : Quaternion.identity), Vector3.one);
Draw.Gizmos.CircleXZ(Vector3.zero, pickNextWaypointDist, GizmoColor * new Color(1, 1, 1, alpha));
Draw.Gizmos.CircleXZ(Vector3.zero, slowdownDistance, Color.Lerp(GizmoColor, Color.red, 0.5f) * new Color(1, 1, 1, alpha));
Draw.Gizmos.CircleXZ(Vector3.zero, endReachedDistance, Color.Lerp(GizmoColor, Color.red, 0.8f) * new Color(1, 1, 1, alpha));
}
}
#endif
protected override int OnUpgradeSerializedData (int version, bool unityThread) {
// Approximately convert from a damping value to a degrees per second value.
if (version < 1) rotationSpeed *= 90;
return base.OnUpgradeSerializedData(version, unityThread);
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: f6eb1402c17e84a9282a7f0f62eb584f
timeCreated: 1491225739
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,392 @@
using UnityEngine;
using System.Collections.Generic;
namespace Pathfinding {
/// <summary>
/// Common interface for all movement scripts in the A* Pathfinding Project.
/// See: <see cref="Pathfinding.AIPath"/>
/// See: <see cref="Pathfinding.RichAI"/>
/// See: <see cref="Pathfinding.AILerp"/>
/// </summary>
public interface IAstarAI {
/// <summary>
/// Radius of the agent in world units.
/// This is visualized in the scene view as a yellow cylinder around the character.
///
/// Note: The <see cref="Pathfinding.AILerp"/> script doesn't really have any use of knowing the radius or the height of the character, so this property will always return 0 in that script.
/// </summary>
float radius { get; set; }
/// <summary>
/// Height of the agent in world units.
/// This is visualized in the scene view as a yellow cylinder around the character.
///
/// This value is currently only used if an RVOController is attached to the same GameObject, otherwise it is only used for drawing nice gizmos in the scene view.
/// However since the height value is used for some things, the radius field is always visible for consistency and easier visualization of the character.
/// That said, it may be used for something in a future release.
///
/// Note: The <see cref="Pathfinding.AILerp"/> script doesn't really have any use of knowing the radius or the height of the character, so this property will always return 0 in that script.
/// </summary>
float height { get; set; }
/// <summary>
/// Position of the agent.
/// In world space.
/// See: <see cref="rotation"/>
///
/// If you want to move the agent you may use <see cref="Teleport"/> or <see cref="Move"/>.
/// </summary>
Vector3 position { get; }
/// <summary>
/// Rotation of the agent.
/// In world space.
/// See: <see cref="position"/>
/// </summary>
Quaternion rotation { get; set; }
/// <summary>Max speed in world units per second</summary>
float maxSpeed { get; set; }
/// <summary>
/// Actual velocity that the agent is moving with.
/// In world units per second.
///
/// See: <see cref="desiredVelocity"/>
/// </summary>
Vector3 velocity { get; }
/// <summary>
/// Velocity that this agent wants to move with.
/// Includes gravity and local avoidance if applicable.
/// In world units per second.
///
/// See: <see cref="velocity"/>
/// </summary>
Vector3 desiredVelocity { get; }
/// <summary>
/// Approximate remaining distance along the current path to the end of the path.
/// The RichAI movement script approximates this distance since it is quite expensive to calculate the real distance.
/// However it will be accurate when the agent is within 1 corner of the destination.
/// You can use <see cref="GetRemainingPath"/> to calculate the actual remaining path more precisely.
///
/// The AIPath and AILerp scripts use a more accurate distance calculation at all times.
///
/// If the agent does not currently have a path, then positive infinity will be returned.
///
/// Note: This is the distance to the end of the path, which may or may not be at the <see cref="destination"/>. If the character cannot reach the destination it will try to move as close as possible to it.
///
/// Warning: Since path requests are asynchronous, there is a small delay between a path request being sent and this value being updated with the new calculated path.
///
/// See: <see cref="reachedDestination"/>
/// See: <see cref="reachedEndOfPath"/>
/// See: <see cref="pathPending"/>
/// </summary>
float remainingDistance { get; }
/// <summary>
/// True if the ai has reached the <see cref="destination"/>.
/// This is a best effort calculation to see if the <see cref="destination"/> has been reached.
/// For the AIPath/RichAI scripts, this is when the character is within <see cref="AIPath.endReachedDistance"/> world units from the <see cref="destination"/>.
/// For the AILerp script it is when the character is at the destination (±a very small margin).
///
/// This value will be updated immediately when the <see cref="destination"/> is changed (in contrast to <see cref="reachedEndOfPath)"/>, however since path requests are asynchronous
/// it will use an approximation until it sees the real path result. What this property does is to check the distance to the end of the current path, and add to that the distance
/// from the end of the path to the <see cref="destination"/> (i.e. is assumes it is possible to move in a straight line between the end of the current path to the destination) and then checks if that total
/// distance is less than <see cref="endReachedDistance"/>. This property is therefore only a best effort, but it will work well for almost all use cases.
///
/// Furthermore it will not report that the destination is reached if the destination is above the head of the character or more than half the <see cref="height"/> of the character below its feet
/// (so if you have a multilevel building, it is important that you configure the <see cref="height"/> of the character correctly).
///
/// The cases which could be problematic are if an agent is standing next to a very thin wall and the destination suddenly changes to the other side of that thin wall.
/// During the time that it takes for the path to be calculated the agent may see itself as alredy having reached the destination because the destination only moved a very small distance (the wall was thin),
/// even though it may actually be quite a long way around the wall to the other side.
///
/// In contrast to <see cref="reachedEndOfPath"/>, this property is immediately updated when the <see cref="destination"/> is changed.
///
/// <code>
/// IEnumerator Start () {
/// ai.destination = somePoint;
/// // Start to search for a path to the destination immediately
/// ai.SearchPath();
/// // Wait until the agent has reached the destination
/// while (!ai.reachedDestination) {
/// yield return null;
/// }
/// // The agent has reached the destination now
/// }
/// </code>
///
/// See: <see cref="AIPath.endReachedDistance"/>
/// See: <see cref="remainingDistance"/>
/// See: <see cref="reachedEndOfPath"/>
/// </summary>
bool reachedDestination { get; }
/// <summary>
/// True if the agent has reached the end of the current path.
///
/// Note that setting the <see cref="destination"/> does not immediately update the path, nor is there any guarantee that the
/// AI will actually be able to reach the destination that you set. The AI will try to get as close as possible.
/// Often you want to use <see cref="reachedDestination"/> instead which is easier to work with.
///
/// It is very hard to provide a method for detecting if the AI has reached the <see cref="destination"/> that works across all different games
/// because the destination may not even lie on the navmesh and how that is handled differs from game to game (see also the code snippet in the docs for <see cref="destination)"/>.
///
/// See: <see cref="remainingDistance"/>
/// See: <see cref="reachedDestination"/>
/// </summary>
bool reachedEndOfPath { get; }
/// <summary>
/// Position in the world that this agent should move to.
///
/// If no destination has been set yet, then (+infinity, +infinity, +infinity) will be returned.
///
/// Note that setting this property does not immediately cause the agent to recalculate its path.
/// So it may take some time before the agent starts to move towards this point.
/// Most movement scripts have a repathRate field which indicates how often the agent looks
/// for a new path. You can also call the <see cref="SearchPath"/> method to immediately
/// start to search for a new path. Paths are calculated asynchronously so when an agent starts to
/// search for path it may take a few frames (usually 1 or 2) until the result is available.
/// During this time the <see cref="pathPending"/> property will return true.
///
/// If you are setting a destination and then want to know when the agent has reached that destination
/// then you could either use <see cref="reachedDestination"/> (recommended) or check both <see cref="pathPending"/> and <see cref="reachedEndOfPath"/>.
/// Check the documentation for the respective fields to learn about their differences.
///
/// <code>
/// IEnumerator Start () {
/// ai.destination = somePoint;
/// // Start to search for a path to the destination immediately
/// ai.SearchPath();
/// // Wait until the agent has reached the destination
/// while (!ai.reachedDestination) {
/// yield return null;
/// }
/// // The agent has reached the destination now
/// }
/// </code>
/// <code>
/// IEnumerator Start () {
/// ai.destination = somePoint;
/// // Start to search for a path to the destination immediately
/// // Note that the result may not become available until after a few frames
/// // ai.pathPending will be true while the path is being calculated
/// ai.SearchPath();
/// // Wait until we know for sure that the agent has calculated a path to the destination we set above
/// while (ai.pathPending || !ai.reachedEndOfPath) {
/// yield return null;
/// }
/// // The agent has reached the destination now
/// }
/// </code>
/// </summary>
Vector3 destination { get; set; }
/// <summary>
/// Enables or disables recalculating the path at regular intervals.
/// Setting this to false does not stop any active path requests from being calculated or stop it from continuing to follow the current path.
///
/// Note that this only disables automatic path recalculations. If you call the <see cref="SearchPath()"/> method a path will still be calculated.
///
/// See: <see cref="canMove"/>
/// See: <see cref="isStopped"/>
/// </summary>
bool canSearch { get; set; }
/// <summary>
/// Enables or disables movement completely.
/// If you want the agent to stand still, but still react to local avoidance and use gravity: use <see cref="isStopped"/> instead.
///
/// This is also useful if you want to have full control over when the movement calculations run.
/// Take a look at <see cref="MovementUpdate"/>
///
/// See: <see cref="canSearch"/>
/// See: <see cref="isStopped"/>
/// </summary>
bool canMove { get; set; }
/// <summary>True if this agent currently has a path that it follows</summary>
bool hasPath { get; }
/// <summary>True if a path is currently being calculated</summary>
bool pathPending { get; }
/// <summary>
/// Gets or sets if the agent should stop moving.
/// If this is set to true the agent will immediately start to slow down as quickly as it can to come to a full stop.
/// The agent will still react to local avoidance and gravity (if applicable), but it will not try to move in any particular direction.
///
/// The current path of the agent will not be cleared, so when this is set
/// to false again the agent will continue moving along the previous path.
///
/// This is a purely user-controlled parameter, so for example it is not set automatically when the agent stops
/// moving because it has reached the target. Use <see cref="reachedEndOfPath"/> for that.
///
/// If this property is set to true while the agent is traversing an off-mesh link (RichAI script only), then the agent will
/// continue traversing the link and stop once it has completed it.
///
/// Note: This is not the same as the <see cref="canMove"/> setting which some movement scripts have. The <see cref="canMove"/> setting
/// disables movement calculations completely (which among other things makes it not be affected by local avoidance or gravity).
/// For the AILerp movement script which doesn't use gravity or local avoidance anyway changing this property is very similar to
/// changing <see cref="canMove"/>.
///
/// The <see cref="steeringTarget"/> property will continue to indicate the point which the agent would move towards if it would not be stopped.
/// </summary>
bool isStopped { get; set; }
/// <summary>
/// Point on the path which the agent is currently moving towards.
/// This is usually a point a small distance ahead of the agent
/// or the end of the path.
///
/// If the agent does not have a path at the moment, then the agent's current position will be returned.
/// </summary>
Vector3 steeringTarget { get; }
/// <summary>
/// Called when the agent recalculates its path.
/// This is called both for automatic path recalculations (see <see cref="canSearch)"/> and manual ones (see <see cref="SearchPath)"/>.
///
/// See: Take a look at the <see cref="Pathfinding.AIDestinationSetter"/> source code for an example of how it can be used.
/// </summary>
System.Action onSearchPath { get; set; }
/// <summary>
/// Fills buffer with the remaining path.
///
/// <code>
/// var buffer = new List<Vector3>();
///
/// ai.GetRemainingPath(buffer, out bool stale);
/// for (int i = 0; i < buffer.Count - 1; i++) {
/// Debug.DrawLine(buffer[i], buffer[i+1], Color.red);
/// }
/// </code>
/// [Open online documentation to see images]
/// </summary>
/// <param name="buffer">The buffer will be cleared and replaced with the path. The first point is the current position of the agent.</param>
/// <param name="stale">May be true if the path is invalid in some way. For example if the agent has no path or (for the RichAI script only) if the agent has detected that some nodes in the path have been destroyed.</param>
void GetRemainingPath(List<Vector3> buffer, out bool stale);
/// <summary>
/// Recalculate the current path.
/// You can for example use this if you want very quick reaction times when you have changed the <see cref="destination"/>
/// so that the agent does not have to wait until the next automatic path recalculation (see <see cref="canSearch)"/>.
///
/// If there is an ongoing path calculation, it will be canceled, so make sure you leave time for the paths to get calculated before calling this function again.
/// A canceled path will show up in the log with the message "Canceled by script" (see <see cref="Seeker.CancelCurrentPathRequest())"/>.
///
/// If no <see cref="destination"/> has been set yet then nothing will be done.
///
/// Note: The path result may not become available until after a few frames.
/// During the calculation time the <see cref="pathPending"/> property will return true.
///
/// See: <see cref="pathPending"/>
/// </summary>
void SearchPath();
/// <summary>
/// Make the AI follow the specified path.
/// In case the path has not been calculated, the script will call seeker.StartPath to calculate it.
/// This means the AI may not actually start to follow the path until in a few frames when the path has been calculated.
/// The <see cref="pathPending"/> field will as usual return true while the path is being calculated.
///
/// In case the path has already been calculated it will immediately replace the current path the AI is following.
/// This is useful if you want to replace how the AI calculates its paths.
/// Note that if you calculate the path using seeker.StartPath then this script will already pick it up because it is listening for
/// all paths that the Seeker finishes calculating. In that case you do not need to call this function.
///
/// If you pass null as a parameter then the current path will be cleared and the agent will stop moving.
/// Note than unless you have also disabled <see cref="canSearch"/> then the agent will soon recalculate its path and start moving again.
///
/// You can disable the automatic path recalculation by setting the <see cref="canSearch"/> field to false.
///
/// <code>
/// // Disable the automatic path recalculation
/// ai.canSearch = false;
/// var pointToAvoid = enemy.position;
/// // Make the AI flee from the enemy.
/// // The path will be about 20 world units long (the default cost of moving 1 world unit is 1000).
/// var path = FleePath.Construct(ai.position, pointToAvoid, 1000 * 20);
/// ai.SetPath(path);
///
/// // If you want to make use of properties like ai.reachedDestination or ai.remainingDistance or similar
/// // you should also set the destination property to something reasonable.
/// // Since the agent's own path recalculation is disabled, setting this will not affect how the paths are calculated.
/// // ai.destination = ...
/// </code>
/// </summary>
void SetPath(Path path);
/// <summary>
/// Instantly move the agent to a new position.
/// This will trigger a path recalculation (if clearPath is true, which is the default) so if you want to teleport the agent and change its <see cref="destination"/>
/// it is recommended that you set the <see cref="destination"/> before calling this method.
///
/// The current path will be cleared by default.
///
/// See: Works similarly to Unity's NavmeshAgent.Warp.
/// See: <see cref="SearchPath"/>
/// </summary>
void Teleport(Vector3 newPosition, bool clearPath = true);
/// <summary>
/// Move the agent.
///
/// This is intended for external movement forces such as those applied by wind, conveyor belts, knockbacks etc.
///
/// Some movement scripts may ignore this completely (notably the AILerp script) if it does not have
/// any concept of being moved externally.
///
/// The agent will not be moved immediately when calling this method. Instead this offset will be stored and then
/// applied the next time the agent runs its movement calculations (which is usually later this frame or the next frame).
/// If you want to move the agent immediately then call:
/// <code>
/// ai.Move(someVector);
/// ai.FinalizeMovement(ai.position, ai.rotation);
/// </code>
/// </summary>
/// <param name="deltaPosition">Direction and distance to move the agent in world space.</param>
void Move(Vector3 deltaPosition);
/// <summary>
/// Calculate how the character wants to move during this frame.
///
/// Note that this does not actually move the character. You need to call <see cref="FinalizeMovement"/> for that.
/// This is called automatically unless <see cref="canMove"/> is false.
///
/// To handle movement yourself you can disable <see cref="canMove"/> and call this method manually.
/// This code will replicate the normal behavior of the component:
/// <code>
/// void Update () {
/// // Disable the AIs own movement code
/// ai.canMove = false;
/// Vector3 nextPosition;
/// Quaternion nextRotation;
/// // Calculate how the AI wants to move
/// ai.MovementUpdate(Time.deltaTime, out nextPosition, out nextRotation);
/// // Modify nextPosition and nextRotation in any way you wish
/// // Actually move the AI
/// ai.FinalizeMovement(nextPosition, nextRotation);
/// }
/// </code>
/// </summary>
/// <param name="deltaTime">time to simulate movement for. Usually set to Time.deltaTime.</param>
/// <param name="nextPosition">the position that the agent wants to move to during this frame.</param>
/// <param name="nextRotation">the rotation that the agent wants to rotate to during this frame.</param>
void MovementUpdate(float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation);
/// <summary>
/// Move the agent.
/// To be called as the last step when you are handling movement manually.
///
/// The movement will be clamped to the navmesh if applicable (this is done for the RichAI movement script).
///
/// See: <see cref="MovementUpdate"/> for a code example.
/// </summary>
void FinalizeMovement(Vector3 nextPosition, Quaternion nextRotation);
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b7438f3f6b9404f05ab7f584f92aa7d5
timeCreated: 1495013922
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,4 @@
// This file has been removed from the project. Since UnityPackages cannot
// delete files, only replace them, this message is left here to prevent old
// files from causing compiler errors

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 20549335d45df4a329ece093b865221b
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}

View File

@@ -0,0 +1,507 @@
using UnityEngine;
using System.Collections.Generic;
#if UNITY_5_5_OR_NEWER
using UnityEngine.Profiling;
#endif
namespace Pathfinding {
/// <summary>
/// Handles path calls for a single unit.
/// \ingroup relevant
/// This is a component which is meant to be attached to a single unit (AI, Robot, Player, whatever) to handle its pathfinding calls.
/// It also handles post-processing of paths using modifiers.
///
/// [Open online documentation to see images]
///
/// See: calling-pathfinding (view in online documentation for working links)
/// See: modifiers (view in online documentation for working links)
/// </summary>
[AddComponentMenu("Pathfinding/Seeker")]
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_seeker.php")]
public class Seeker : VersionedMonoBehaviour {
/// <summary>
/// Enables drawing of the last calculated path using Gizmos.
/// The path will show up in green.
///
/// See: OnDrawGizmos
/// </summary>
public bool drawGizmos = true;
/// <summary>
/// Enables drawing of the non-postprocessed path using Gizmos.
/// The path will show up in orange.
///
/// Requires that <see cref="drawGizmos"/> is true.
///
/// This will show the path before any post processing such as smoothing is applied.
///
/// See: drawGizmos
/// See: OnDrawGizmos
/// </summary>
public bool detailedGizmos;
/// <summary>Path modifier which tweaks the start and end points of a path</summary>
[HideInInspector]
public StartEndModifier startEndModifier = new StartEndModifier();
/// <summary>
/// The tags which the Seeker can traverse.
///
/// Note: This field is a bitmask.
/// See: bitmasks (view in online documentation for working links)
/// </summary>
[HideInInspector]
public int traversableTags = -1;
/// <summary>
/// Penalties for each tag.
/// Tag 0 which is the default tag, will have added a penalty of tagPenalties[0].
/// These should only be positive values since the A* algorithm cannot handle negative penalties.
///
/// Note: This array should always have a length of 32 otherwise the system will ignore it.
///
/// See: Pathfinding.Path.tagPenalties
/// </summary>
[HideInInspector]
public int[] tagPenalties = new int[32];
/// <summary>
/// Graphs that this Seeker can use.
/// This field determines which graphs will be considered when searching for the start and end nodes of a path.
/// It is useful in numerous situations, for example if you want to make one graph for small units and one graph for large units.
///
/// This is a bitmask so if you for example want to make the agent only use graph index 3 then you can set this to:
/// <code> seeker.graphMask = 1 << 3; </code>
///
/// See: bitmasks (view in online documentation for working links)
///
/// Note that this field only stores which graph indices that are allowed. This means that if the graphs change their ordering
/// then this mask may no longer be correct.
///
/// If you know the name of the graph you can use the <see cref="Pathfinding.GraphMask.FromGraphName"/> method:
/// <code>
/// GraphMask mask1 = GraphMask.FromGraphName("My Grid Graph");
/// GraphMask mask2 = GraphMask.FromGraphName("My Other Grid Graph");
///
/// NNConstraint nn = NNConstraint.Default;
///
/// nn.graphMask = mask1 | mask2;
///
/// // Find the node closest to somePoint which is either in 'My Grid Graph' OR in 'My Other Grid Graph'
/// var info = AstarPath.active.GetNearest(somePoint, nn);
/// </code>
///
/// Some overloads of the <see cref="StartPath"/> methods take a graphMask parameter. If those overloads are used then they
/// will override the graph mask for that path request.
///
/// [Open online documentation to see images]
///
/// See: multiple-agent-types (view in online documentation for working links)
/// </summary>
[HideInInspector]
public GraphMask graphMask = GraphMask.everything;
/// <summary>Used for serialization backwards compatibility</summary>
[UnityEngine.Serialization.FormerlySerializedAs("graphMask")]
int graphMaskCompatibility = -1;
/// <summary>
/// Callback for when a path is completed.
/// Movement scripts should register to this delegate.\n
/// A temporary callback can also be set when calling StartPath, but that delegate will only be called for that path
/// </summary>
public OnPathDelegate pathCallback;
/// <summary>Called before pathfinding is started</summary>
public OnPathDelegate preProcessPath;
/// <summary>Called after a path has been calculated, right before modifiers are executed.</summary>
public OnPathDelegate postProcessPath;
/// <summary>Used for drawing gizmos</summary>
[System.NonSerialized]
List<Vector3> lastCompletedVectorPath;
/// <summary>Used for drawing gizmos</summary>
[System.NonSerialized]
List<GraphNode> lastCompletedNodePath;
/// <summary>The current path</summary>
[System.NonSerialized]
protected Path path;
/// <summary>Previous path. Used to draw gizmos</summary>
[System.NonSerialized]
private Path prevPath;
/// <summary>Cached delegate to avoid allocating one every time a path is started</summary>
private readonly OnPathDelegate onPathDelegate;
/// <summary>Temporary callback only called for the current path. This value is set by the StartPath functions</summary>
private OnPathDelegate tmpPathCallback;
/// <summary>The path ID of the last path queried</summary>
protected uint lastPathID;
/// <summary>Internal list of all modifiers</summary>
readonly List<IPathModifier> modifiers = new List<IPathModifier>();
public enum ModifierPass {
PreProcess,
// An obsolete item occupied index 1 previously
PostProcess = 2,
}
public Seeker () {
onPathDelegate = OnPathComplete;
}
/// <summary>Initializes a few variables</summary>
protected override void Awake () {
base.Awake();
startEndModifier.Awake(this);
}
/// <summary>
/// Path that is currently being calculated or was last calculated.
/// You should rarely have to use this. Instead get the path when the path callback is called.
///
/// See: pathCallback
/// </summary>
public Path GetCurrentPath () {
return path;
}
/// <summary>
/// Stop calculating the current path request.
/// If this Seeker is currently calculating a path it will be canceled.
/// The callback (usually to a method named OnPathComplete) will soon be called
/// with a path that has the 'error' field set to true.
///
/// This does not stop the character from moving, it just aborts
/// the path calculation.
/// </summary>
/// <param name="pool">If true then the path will be pooled when the pathfinding system is done with it.</param>
public void CancelCurrentPathRequest (bool pool = true) {
if (!IsDone()) {
path.FailWithError("Canceled by script (Seeker.CancelCurrentPathRequest)");
if (pool) {
// Make sure the path has had its reference count incremented and decremented once.
// If this is not done the system will think no pooling is used at all and will not pool the path.
// The particular object that is used as the parameter (in this case 'path') doesn't matter at all
// it just has to be *some* object.
path.Claim(path);
path.Release(path);
}
}
}
/// <summary>
/// Cleans up some variables.
/// Releases any eventually claimed paths.
/// Calls OnDestroy on the <see cref="startEndModifier"/>.
///
/// See: <see cref="ReleaseClaimedPath"/>
/// See: <see cref="startEndModifier"/>
/// </summary>
public void OnDestroy () {
ReleaseClaimedPath();
startEndModifier.OnDestroy(this);
}
/// <summary>
/// Releases the path used for gizmos (if any).
/// The seeker keeps the latest path claimed so it can draw gizmos.
/// In some cases this might not be desireable and you want it released.
/// In that case, you can call this method to release it (not that path gizmos will then not be drawn).
///
/// If you didn't understand anything from the description above, you probably don't need to use this method.
///
/// See: pooling (view in online documentation for working links)
/// </summary>
void ReleaseClaimedPath () {
if (prevPath != null) {
prevPath.Release(this, true);
prevPath = null;
}
}
/// <summary>Called by modifiers to register themselves</summary>
public void RegisterModifier (IPathModifier modifier) {
modifiers.Add(modifier);
// Sort the modifiers based on their specified order
modifiers.Sort((a, b) => a.Order.CompareTo(b.Order));
}
/// <summary>Called by modifiers when they are disabled or destroyed</summary>
public void DeregisterModifier (IPathModifier modifier) {
modifiers.Remove(modifier);
}
/// <summary>
/// Post Processes the path.
/// This will run any modifiers attached to this GameObject on the path.
/// This is identical to calling RunModifiers(ModifierPass.PostProcess, path)
/// See: RunModifiers
/// \since Added in 3.2
/// </summary>
public void PostProcess (Path path) {
RunModifiers(ModifierPass.PostProcess, path);
}
/// <summary>Runs modifiers on a path</summary>
public void RunModifiers (ModifierPass pass, Path path) {
if (pass == ModifierPass.PreProcess) {
if (preProcessPath != null) preProcessPath(path);
for (int i = 0; i < modifiers.Count; i++) modifiers[i].PreProcess(path);
} else if (pass == ModifierPass.PostProcess) {
Profiler.BeginSample("Running Path Modifiers");
// Call delegates if they exist
if (postProcessPath != null) postProcessPath(path);
// Loop through all modifiers and apply post processing
for (int i = 0; i < modifiers.Count; i++) modifiers[i].Apply(path);
Profiler.EndSample();
}
}
/// <summary>
/// Is the current path done calculating.
/// Returns true if the current <see cref="path"/> has been returned or if the <see cref="path"/> is null.
///
/// Note: Do not confuse this with Pathfinding.Path.IsDone. They usually return the same value, but not always
/// since the path might be completely calculated, but it has not yet been processed by the Seeker.
///
/// \since Added in 3.0.8
/// Version: Behaviour changed in 3.2
/// </summary>
public bool IsDone () {
return path == null || path.PipelineState >= PathState.Returned;
}
/// <summary>
/// Called when a path has completed.
/// This should have been implemented as optional parameter values, but that didn't seem to work very well with delegates (the values weren't the default ones)
/// See: OnPathComplete(Path,bool,bool)
/// </summary>
void OnPathComplete (Path path) {
OnPathComplete(path, true, true);
}
/// <summary>
/// Called when a path has completed.
/// Will post process it and return it by calling <see cref="tmpPathCallback"/> and <see cref="pathCallback"/>
/// </summary>
void OnPathComplete (Path p, bool runModifiers, bool sendCallbacks) {
if (p != null && p != path && sendCallbacks) {
return;
}
if (this == null || p == null || p != path)
return;
if (!path.error && runModifiers) {
// This will send the path for post processing to modifiers attached to this Seeker
RunModifiers(ModifierPass.PostProcess, path);
}
if (sendCallbacks) {
p.Claim(this);
lastCompletedNodePath = p.path;
lastCompletedVectorPath = p.vectorPath;
// This will send the path to the callback (if any) specified when calling StartPath
if (tmpPathCallback != null) {
tmpPathCallback(p);
}
// This will send the path to any script which has registered to the callback
if (pathCallback != null) {
pathCallback(p);
}
// Note: it is important that #prevPath is kept alive (i.e. not pooled)
// if we are drawing gizmos.
// It is also important that #path is kept alive since it can be returned
// from the GetCurrentPath method.
// Since #path will be copied to #prevPath it is sufficient that #prevPath
// is kept alive until it is replaced.
// Recycle the previous path to reduce the load on the GC
if (prevPath != null) {
prevPath.Release(this, true);
}
prevPath = p;
}
}
/// <summary>
/// Returns a new path instance.
/// The path will be taken from the path pool if path recycling is turned on.\n
/// This path can be sent to <see cref="StartPath(Path,OnPathDelegate,int)"/> with no change, but if no change is required <see cref="StartPath(Vector3,Vector3,OnPathDelegate)"/> does just that.
/// <code>
/// var seeker = GetComponent<Seeker>();
/// Path p = seeker.GetNewPath (transform.position, transform.position+transform.forward*100);
/// // Disable heuristics on just this path for example
/// p.heuristic = Heuristic.None;
/// seeker.StartPath (p, OnPathComplete);
/// </code>
/// Deprecated: Use ABPath.Construct(start, end, null) instead.
/// </summary>
[System.Obsolete("Use ABPath.Construct(start, end, null) instead")]
public ABPath GetNewPath (Vector3 start, Vector3 end) {
// Construct a path with start and end points
return ABPath.Construct(start, end, null);
}
/// <summary>
/// Call this function to start calculating a path.
/// Since this method does not take a callback parameter, you should set the <see cref="pathCallback"/> field before calling this method.
/// </summary>
/// <param name="start">The start point of the path</param>
/// <param name="end">The end point of the path</param>
public Path StartPath (Vector3 start, Vector3 end) {
return StartPath(start, end, null);
}
/// <summary>
/// Call this function to start calculating a path.
///
/// callback will be called when the path has completed.
/// Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed)
/// </summary>
/// <param name="start">The start point of the path</param>
/// <param name="end">The end point of the path</param>
/// <param name="callback">The function to call when the path has been calculated</param>
public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback) {
return StartPath(ABPath.Construct(start, end, null), callback);
}
/// <summary>
/// Call this function to start calculating a path.
///
/// callback will be called when the path has completed.
/// Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed)
/// </summary>
/// <param name="start">The start point of the path</param>
/// <param name="end">The end point of the path</param>
/// <param name="callback">The function to call when the path has been calculated</param>
/// <param name="graphMask">Mask used to specify which graphs should be searched for close nodes. See #Pathfinding.NNConstraint.graphMask. This will override #graphMask for this path request.</param>
public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback, GraphMask graphMask) {
return StartPath(ABPath.Construct(start, end, null), callback, graphMask);
}
/// <summary>
/// Call this function to start calculating a path.
///
/// The callback will be called when the path has been calculated (which may be several frames into the future).
/// The callback will not be called if a new path request is started before this path request has been calculated.
///
/// Version: Since 3.8.3 this method works properly if a MultiTargetPath is used.
/// It now behaves identically to the StartMultiTargetPath(MultiTargetPath) method.
///
/// Version: Since 4.1.x this method will no longer overwrite the graphMask on the path unless it is explicitly passed as a parameter (see other overloads of this method).
/// </summary>
/// <param name="p">The path to start calculating</param>
/// <param name="callback">The function to call when the path has been calculated</param>
public Path StartPath (Path p, OnPathDelegate callback = null) {
// Set the graph mask only if the user has not changed it from the default value.
// This is not perfect as the user may have wanted it to be precisely -1
// however it is the best detection that I can do.
// The non-default check is primarily for compatibility reasons to avoid breaking peoples existing code.
// The StartPath overloads with an explicit graphMask field should be used instead to set the graphMask.
if (p.nnConstraint.graphMask == -1) p.nnConstraint.graphMask = graphMask;
StartPathInternal(p, callback);
return p;
}
/// <summary>
/// Call this function to start calculating a path.
///
/// The callback will be called when the path has been calculated (which may be several frames into the future).
/// The callback will not be called if a new path request is started before this path request has been calculated.
///
/// Version: Since 3.8.3 this method works properly if a MultiTargetPath is used.
/// It now behaves identically to the StartMultiTargetPath(MultiTargetPath) method.
/// </summary>
/// <param name="p">The path to start calculating</param>
/// <param name="callback">The function to call when the path has been calculated</param>
/// <param name="graphMask">Mask used to specify which graphs should be searched for close nodes. See #Pathfinding.GraphMask. This will override #graphMask for this path request.</param>
public Path StartPath (Path p, OnPathDelegate callback, GraphMask graphMask) {
p.nnConstraint.graphMask = graphMask;
StartPathInternal(p, callback);
return p;
}
/// <summary>Internal method to start a path and mark it as the currently active path</summary>
void StartPathInternal (Path p, OnPathDelegate callback) {
p.callback += onPathDelegate;
p.enabledTags = traversableTags;
p.tagPenalties = tagPenalties;
// Cancel a previously requested path is it has not been processed yet and also make sure that it has not been recycled and used somewhere else
if (path != null && path.PipelineState <= PathState.Processing && path.CompleteState != PathCompleteState.Error && lastPathID == path.pathID) {
path.FailWithError("Canceled path because a new one was requested.\n"+
"This happens when a new path is requested from the seeker when one was already being calculated.\n" +
"For example if a unit got a new order, you might request a new path directly instead of waiting for the now" +
" invalid path to be calculated. Which is probably what you want.\n" +
"If you are getting this a lot, you might want to consider how you are scheduling path requests.");
// No callback will be sent for the canceled path
}
// Set p as the active path
path = p;
tmpPathCallback = callback;
// Save the path id so we can make sure that if we cancel a path (see above) it should not have been recycled yet.
lastPathID = path.pathID;
// Pre process the path
RunModifiers(ModifierPass.PreProcess, path);
// Send the request to the pathfinder
AstarPath.StartPath(path);
}
/// <summary>Draws gizmos for the Seeker</summary>
public void OnDrawGizmos () {
if (lastCompletedNodePath == null || !drawGizmos) {
return;
}
if (detailedGizmos) {
Gizmos.color = new Color(0.7F, 0.5F, 0.1F, 0.5F);
if (lastCompletedNodePath != null) {
for (int i = 0; i < lastCompletedNodePath.Count-1; i++) {
Gizmos.DrawLine((Vector3)lastCompletedNodePath[i].position, (Vector3)lastCompletedNodePath[i+1].position);
}
}
}
Gizmos.color = new Color(0, 1F, 0, 1F);
if (lastCompletedVectorPath != null) {
for (int i = 0; i < lastCompletedVectorPath.Count-1; i++) {
Gizmos.DrawLine(lastCompletedVectorPath[i], lastCompletedVectorPath[i+1]);
}
}
}
protected override int OnUpgradeSerializedData (int version, bool unityThread) {
if (graphMaskCompatibility != -1) {
Debug.Log("Loaded " + graphMaskCompatibility + " " + graphMask.value);
graphMask = graphMaskCompatibility;
graphMaskCompatibility = -1;
}
return base.OnUpgradeSerializedData(version, unityThread);
}
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 373b52eb9bf8c40f785bb6947a1aee66
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}

View File

@@ -0,0 +1,25 @@
using UnityEngine;
using System.Collections.Generic;
namespace Pathfinding.Examples {
/// <summary>Helper script in the example scene 'Turn Based'</summary>
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_examples_1_1_turn_based_a_i.php")]
public class TurnBasedAI : VersionedMonoBehaviour {
public int movementPoints = 2;
public BlockManager blockManager;
public SingleNodeBlocker blocker;
public GraphNode targetNode;
public BlockManager.TraversalProvider traversalProvider;
void Start () {
blocker.BlockAtCurrentPosition();
}
protected override void Awake () {
base.Awake();
// Set the traversal provider to block all nodes that are blocked by a SingleNodeBlocker
// except the SingleNodeBlocker owned by this AI (we don't want to be blocked by ourself)
traversalProvider = new BlockManager.TraversalProvider(blockManager, BlockManager.BlockMode.AllExceptSelector, new List<SingleNodeBlocker>() { blocker });
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 8f95b80c439d6408b9afac9d013922e4
timeCreated: 1453035991
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,733 @@
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding.WindowsStore;
using Pathfinding.Serialization;
#if UNITY_WINRT && !UNITY_EDITOR
//using MarkerMetro.Unity.WinLegacy.IO;
//using MarkerMetro.Unity.WinLegacy.Reflection;
#endif
namespace Pathfinding {
[System.Serializable]
/// <summary>
/// Stores the navigation graphs for the A* Pathfinding System.
/// \ingroup relevant
///
/// An instance of this class is assigned to AstarPath.data, from it you can access all graphs loaded through the <see cref="graphs"/> variable.\n
/// This class also handles a lot of the high level serialization.
/// </summary>
public class AstarData {
/// <summary>Shortcut to AstarPath.active</summary>
public static AstarPath active {
get {
return AstarPath.active;
}
}
#region Fields
/// <summary>
/// Shortcut to the first NavMeshGraph.
/// Updated at scanning time
/// </summary>
public NavMeshGraph navmesh { get; private set; }
#if !ASTAR_NO_GRID_GRAPH
/// <summary>
/// Shortcut to the first GridGraph.
/// Updated at scanning time
/// </summary>
public GridGraph gridGraph { get; private set; }
#endif
#if !ASTAR_NO_POINT_GRAPH
/// <summary>
/// Shortcut to the first PointGraph.
/// Updated at scanning time
/// </summary>
public PointGraph pointGraph { get; private set; }
#endif
/// <summary>
/// All supported graph types.
/// Populated through reflection search
/// </summary>
public System.Type[] graphTypes { get; private set; }
#if ASTAR_FAST_NO_EXCEPTIONS || UNITY_WINRT || UNITY_WEBGL
/// <summary>
/// Graph types to use when building with Fast But No Exceptions for iPhone.
/// If you add any custom graph types, you need to add them to this hard-coded list.
/// </summary>
public static readonly System.Type[] DefaultGraphTypes = new System.Type[] {
#if !ASTAR_NO_GRID_GRAPH
typeof(GridGraph),
#endif
#if !ASTAR_NO_POINT_GRAPH
typeof(PointGraph),
#endif
typeof(NavMeshGraph),
};
#endif
/// <summary>
/// All graphs this instance holds.
/// This will be filled only after deserialization has completed.
/// May contain null entries if graph have been removed.
/// </summary>
[System.NonSerialized]
public NavGraph[] graphs = new NavGraph[0];
//Serialization Settings
/// <summary>
/// Serialized data for all graphs and settings.
/// Stored as a base64 encoded string because otherwise Unity's Undo system would sometimes corrupt the byte data (because it only stores deltas).
///
/// This can be accessed as a byte array from the <see cref="data"/> property.
///
/// \since 3.6.1
/// </summary>
[SerializeField]
string dataString;
/// <summary>
/// Data from versions from before 3.6.1.
/// Used for handling upgrades
/// \since 3.6.1
/// </summary>
[SerializeField]
[UnityEngine.Serialization.FormerlySerializedAs("data")]
private byte[] upgradeData;
/// <summary>Serialized data for all graphs and settings</summary>
private byte[] data {
get {
// Handle upgrading from earlier versions than 3.6.1
if (upgradeData != null && upgradeData.Length > 0) {
data = upgradeData;
upgradeData = null;
}
return dataString != null? System.Convert.FromBase64String(dataString) : null;
}
set {
dataString = value != null? System.Convert.ToBase64String(value) : null;
}
}
/// <summary>
/// Serialized data for cached startup.
/// If set, on start the graphs will be deserialized from this file.
/// </summary>
public TextAsset file_cachedStartup;
/// <summary>
/// Serialized data for cached startup.
///
/// Deprecated: Deprecated since 3.6, AstarData.file_cachedStartup is now used instead
/// </summary>
public byte[] data_cachedStartup;
/// <summary>
/// Should graph-data be cached.
/// Caching the startup means saving the whole graphs - not only the settings - to a file (<see cref="file_cachedStartup)"/> which can
/// be loaded when the game starts. This is usually much faster than scanning the graphs when the game starts. This is configured from the editor under the "Save & Load" tab.
///
/// See: save-load-graphs (view in online documentation for working links)
/// </summary>
[SerializeField]
public bool cacheStartup;
//End Serialization Settings
List<bool> graphStructureLocked = new List<bool>();
#endregion
public byte[] GetData () {
return data;
}
public void SetData (byte[] data) {
this.data = data;
}
/// <summary>Loads the graphs from memory, will load cached graphs if any exists</summary>
public void Awake () {
graphs = new NavGraph[0];
if (cacheStartup && file_cachedStartup != null) {
LoadFromCache();
} else {
DeserializeGraphs();
}
}
/// <summary>
/// Prevent the graph structure from changing during the time this lock is held.
/// This prevents graphs from being added or removed and also prevents graphs from being serialized or deserialized.
/// This is used when e.g an async scan is happening to ensure that for example a graph that is being scanned is not destroyed.
///
/// Each call to this method *must* be paired with exactly one call to <see cref="UnlockGraphStructure"/>.
/// The calls may be nested.
/// </summary>
internal void LockGraphStructure (bool allowAddingGraphs = false) {
graphStructureLocked.Add(allowAddingGraphs);
}
/// <summary>
/// Allows the graph structure to change again.
/// See: <see cref="LockGraphStructure"/>
/// </summary>
internal void UnlockGraphStructure () {
if (graphStructureLocked.Count == 0) throw new System.InvalidOperationException();
graphStructureLocked.RemoveAt(graphStructureLocked.Count - 1);
}
PathProcessor.GraphUpdateLock AssertSafe (bool onlyAddingGraph = false) {
if (graphStructureLocked.Count > 0) {
bool allowAdding = true;
for (int i = 0; i < graphStructureLocked.Count; i++) allowAdding &= graphStructureLocked[i];
if (!(onlyAddingGraph && allowAdding)) throw new System.InvalidOperationException("Graphs cannot be added, removed or serialized while the graph structure is locked. This is the case when a graph is currently being scanned and when executing graph updates and work items.\nHowever as a special case, graphs can be added inside work items.");
}
// Pause the pathfinding threads
var graphLock = active.PausePathfinding();
if (!active.IsInsideWorkItem) {
// Make sure all graph updates and other callbacks are done
// Only do this if this code is not being called from a work item itself as that would cause a recursive wait that could never complete.
// There are some valid cases when this can happen. For example it may be necessary to add a new graph inside a work item.
active.FlushWorkItems();
// Paths that are already calculated and waiting to be returned to the Seeker component need to be
// processed immediately as their results usually depend on graphs that currently exist. If this was
// not done then after destroying a graph one could get a path result with destroyed nodes in it.
active.pathReturnQueue.ReturnPaths(false);
}
return graphLock;
}
/// <summary>
/// Calls the callback with every node in all graphs.
/// This is the easiest way to iterate through every existing node.
///
/// <code>
/// AstarPath.active.data.GetNodes(node => {
/// Debug.Log("I found a node at position " + (Vector3)node.position);
/// });
/// </code>
///
/// See: <see cref="Pathfinding.NavGraph.GetNodes"/> for getting the nodes of a single graph instead of all.
/// See: graph-updates (view in online documentation for working links)
/// </summary>
public void GetNodes (System.Action<GraphNode> callback) {
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] != null) graphs[i].GetNodes(callback);
}
}
/// <summary>
/// Updates shortcuts to the first graph of different types.
/// Hard coding references to some graph types is not really a good thing imo. I want to keep it dynamic and flexible.
/// But these references ease the use of the system, so I decided to keep them.
/// </summary>
public void UpdateShortcuts () {
navmesh = (NavMeshGraph)FindGraphOfType(typeof(NavMeshGraph));
#if !ASTAR_NO_GRID_GRAPH
gridGraph = (GridGraph)FindGraphOfType(typeof(GridGraph));
#endif
#if !ASTAR_NO_POINT_GRAPH
pointGraph = (PointGraph)FindGraphOfType(typeof(PointGraph));
#endif
}
/// <summary>Load from data from <see cref="file_cachedStartup"/></summary>
public void LoadFromCache () {
var graphLock = AssertSafe();
if (file_cachedStartup != null) {
var bytes = file_cachedStartup.bytes;
DeserializeGraphs(bytes);
GraphModifier.TriggerEvent(GraphModifier.EventType.PostCacheLoad);
} else {
Debug.LogError("Can't load from cache since the cache is empty");
}
graphLock.Release();
}
#region Serialization
/// <summary>
/// Serializes all graphs settings to a byte array.
/// See: DeserializeGraphs(byte[])
/// </summary>
public byte[] SerializeGraphs () {
return SerializeGraphs(SerializeSettings.Settings);
}
/// <summary>
/// Serializes all graphs settings and optionally node data to a byte array.
/// See: DeserializeGraphs(byte[])
/// See: Pathfinding.Serialization.SerializeSettings
/// </summary>
public byte[] SerializeGraphs (SerializeSettings settings) {
uint checksum;
return SerializeGraphs(settings, out checksum);
}
/// <summary>
/// Main serializer function.
/// Serializes all graphs to a byte array
/// A similar function exists in the AstarPathEditor.cs script to save additional info
/// </summary>
public byte[] SerializeGraphs (SerializeSettings settings, out uint checksum) {
var graphLock = AssertSafe();
var sr = new AstarSerializer(this, settings, active.gameObject);
sr.OpenSerialize();
sr.SerializeGraphs(graphs);
sr.SerializeExtraInfo();
byte[] bytes = sr.CloseSerialize();
checksum = sr.GetChecksum();
#if ASTARDEBUG
Debug.Log("Got a whole bunch of data, "+bytes.Length+" bytes");
#endif
graphLock.Release();
return bytes;
}
/// <summary>Deserializes graphs from <see cref="data"/></summary>
public void DeserializeGraphs () {
if (data != null) {
DeserializeGraphs(data);
}
}
/// <summary>Destroys all graphs and sets graphs to null</summary>
void ClearGraphs () {
if (graphs == null) return;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] != null) {
((IGraphInternals)graphs[i]).OnDestroy();
graphs[i].active = null;
}
}
graphs = new NavGraph[0];
UpdateShortcuts();
}
public void OnDestroy () {
ClearGraphs();
}
/// <summary>
/// Deserializes graphs from the specified byte array.
/// An error will be logged if deserialization fails.
/// </summary>
public void DeserializeGraphs (byte[] bytes) {
var graphLock = AssertSafe();
ClearGraphs();
DeserializeGraphsAdditive(bytes);
graphLock.Release();
}
/// <summary>
/// Deserializes graphs from the specified byte array additively.
/// An error will be logged if deserialization fails.
/// This function will add loaded graphs to the current ones.
/// </summary>
public void DeserializeGraphsAdditive (byte[] bytes) {
var graphLock = AssertSafe();
try {
if (bytes != null) {
var sr = new AstarSerializer(this, active.gameObject);
if (sr.OpenDeserialize(bytes)) {
DeserializeGraphsPartAdditive(sr);
sr.CloseDeserialize();
} else {
Debug.Log("Invalid data file (cannot read zip).\nThe data is either corrupt or it was saved using a 3.0.x or earlier version of the system");
}
} else {
throw new System.ArgumentNullException("bytes");
}
active.VerifyIntegrity();
} catch (System.Exception e) {
Debug.LogError("Caught exception while deserializing data.\n"+e);
graphs = new NavGraph[0];
}
UpdateShortcuts();
graphLock.Release();
}
/// <summary>Helper function for deserializing graphs</summary>
void DeserializeGraphsPartAdditive (AstarSerializer sr) {
if (graphs == null) graphs = new NavGraph[0];
var gr = new List<NavGraph>(graphs);
// Set an offset so that the deserializer will load
// the graphs with the correct graph indexes
sr.SetGraphIndexOffset(gr.Count);
if (graphTypes == null) FindGraphTypes();
gr.AddRange(sr.DeserializeGraphs(graphTypes));
graphs = gr.ToArray();
sr.DeserializeEditorSettingsCompatibility();
sr.DeserializeExtraInfo();
//Assign correct graph indices.
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] == null) continue;
graphs[i].GetNodes(node => node.GraphIndex = (uint)i);
}
for (int i = 0; i < graphs.Length; i++) {
for (int j = i+1; j < graphs.Length; j++) {
if (graphs[i] != null && graphs[j] != null && graphs[i].guid == graphs[j].guid) {
Debug.LogWarning("Guid Conflict when importing graphs additively. Imported graph will get a new Guid.\nThis message is (relatively) harmless.");
graphs[i].guid = Pathfinding.Util.Guid.NewGuid();
break;
}
}
}
sr.PostDeserialization();
active.hierarchicalGraph.RecalculateIfNecessary();
}
#endregion
/// <summary>
/// Find all graph types supported in this build.
/// Using reflection, the assembly is searched for types which inherit from NavGraph.
/// </summary>
public void FindGraphTypes () {
#if !ASTAR_FAST_NO_EXCEPTIONS && !UNITY_WINRT && !UNITY_WEBGL
var graphList = new List<System.Type>();
foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) {
System.Type[] types = null;
try {
types = assembly.GetTypes();
} catch {
// Ignore type load exceptions and things like that.
// We might not be able to read all assemblies for some reason, but hopefully the relevant types exist in the assemblies that we can read
continue;
}
foreach (var type in types) {
#if NETFX_CORE && !UNITY_EDITOR
System.Type baseType = type.GetTypeInfo().BaseType;
#else
var baseType = type.BaseType;
#endif
while (baseType != null) {
if (System.Type.Equals(baseType, typeof(NavGraph))) {
graphList.Add(type);
break;
}
#if NETFX_CORE && !UNITY_EDITOR
baseType = baseType.GetTypeInfo().BaseType;
#else
baseType = baseType.BaseType;
#endif
}
}
}
graphTypes = graphList.ToArray();
#if ASTARDEBUG
Debug.Log("Found "+graphTypes.Length+" graph types");
#endif
#else
graphTypes = DefaultGraphTypes;
#endif
}
#region GraphCreation
/// <summary>
/// Returns: A System.Type which matches the specified type string. If no mathing graph type was found, null is returned
///
/// Deprecated:
/// </summary>
[System.Obsolete("If really necessary. Use System.Type.GetType instead.")]
public System.Type GetGraphType (string type) {
for (int i = 0; i < graphTypes.Length; i++) {
if (graphTypes[i].Name == type) {
return graphTypes[i];
}
}
return null;
}
/// <summary>
/// Creates a new instance of a graph of type type. If no matching graph type was found, an error is logged and null is returned
/// Returns: The created graph
/// See: <see cref="CreateGraph(System.Type)"/>
///
/// Deprecated:
/// </summary>
[System.Obsolete("Use CreateGraph(System.Type) instead")]
public NavGraph CreateGraph (string type) {
Debug.Log("Creating Graph of type '"+type+"'");
for (int i = 0; i < graphTypes.Length; i++) {
if (graphTypes[i].Name == type) {
return CreateGraph(graphTypes[i]);
}
}
Debug.LogError("Graph type ("+type+") wasn't found");
return null;
}
/// <summary>
/// Creates a new graph instance of type type
/// See: <see cref="CreateGraph(string)"/>
/// </summary>
internal NavGraph CreateGraph (System.Type type) {
var graph = System.Activator.CreateInstance(type) as NavGraph;
graph.active = active;
return graph;
}
/// <summary>
/// Adds a graph of type type to the <see cref="graphs"/> array
///
/// Deprecated:
/// </summary>
[System.Obsolete("Use AddGraph(System.Type) instead")]
public NavGraph AddGraph (string type) {
NavGraph graph = null;
for (int i = 0; i < graphTypes.Length; i++) {
if (graphTypes[i].Name == type) {
graph = CreateGraph(graphTypes[i]);
}
}
if (graph == null) {
Debug.LogError("No NavGraph of type '"+type+"' could be found");
return null;
}
AddGraph(graph);
return graph;
}
/// <summary>
/// Adds a graph of type type to the <see cref="graphs"/> array.
/// See: runtime-graphs (view in online documentation for working links)
/// </summary>
public NavGraph AddGraph (System.Type type) {
NavGraph graph = null;
for (int i = 0; i < graphTypes.Length; i++) {
if (System.Type.Equals(graphTypes[i], type)) {
graph = CreateGraph(graphTypes[i]);
}
}
if (graph == null) {
Debug.LogError("No NavGraph of type '"+type+"' could be found, "+graphTypes.Length+" graph types are avaliable");
return null;
}
AddGraph(graph);
return graph;
}
/// <summary>Adds the specified graph to the <see cref="graphs"/> array</summary>
void AddGraph (NavGraph graph) {
// Make sure to not interfere with pathfinding
var graphLock = AssertSafe(true);
// Try to fill in an empty position
bool foundEmpty = false;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] == null) {
graphs[i] = graph;
graph.graphIndex = (uint)i;
foundEmpty = true;
break;
}
}
if (!foundEmpty) {
if (graphs != null && graphs.Length >= GraphNode.MaxGraphIndex) {
throw new System.Exception("Graph Count Limit Reached. You cannot have more than " + GraphNode.MaxGraphIndex + " graphs.");
}
// Add a new entry to the list
var graphList = new List<NavGraph>(graphs ?? new NavGraph[0]);
graphList.Add(graph);
graphs = graphList.ToArray();
graph.graphIndex = (uint)(graphs.Length-1);
}
UpdateShortcuts();
graph.active = active;
graphLock.Release();
}
/// <summary>
/// Removes the specified graph from the <see cref="graphs"/> array and Destroys it in a safe manner.
/// To avoid changing graph indices for the other graphs, the graph is simply nulled in the array instead
/// of actually removing it from the array.
/// The empty position will be reused if a new graph is added.
///
/// Returns: True if the graph was sucessfully removed (i.e it did exist in the <see cref="graphs"/> array). False otherwise.
///
/// Version: Changed in 3.2.5 to call SafeOnDestroy before removing
/// and nulling it in the array instead of removing the element completely in the <see cref="graphs"/> array.
/// </summary>
public bool RemoveGraph (NavGraph graph) {
// Make sure the pathfinding threads are stopped
// If we don't wait until pathfinding that is potentially running on
// this graph right now we could end up with NullReferenceExceptions
var graphLock = AssertSafe();
((IGraphInternals)graph).OnDestroy();
graph.active = null;
int i = System.Array.IndexOf(graphs, graph);
if (i != -1) graphs[i] = null;
UpdateShortcuts();
graphLock.Release();
return i != -1;
}
#endregion
#region GraphUtility
/// <summary>
/// Returns the graph which contains the specified node.
/// The graph must be in the <see cref="graphs"/> array.
///
/// Returns: Returns the graph which contains the node. Null if the graph wasn't found
/// </summary>
public static NavGraph GetGraph (GraphNode node) {
if (node == null) return null;
AstarPath script = AstarPath.active;
if (script == null) return null;
AstarData data = script.data;
if (data == null || data.graphs == null) return null;
uint graphIndex = node.GraphIndex;
if (graphIndex >= data.graphs.Length) {
return null;
}
return data.graphs[(int)graphIndex];
}
/// <summary>Returns the first graph which satisfies the predicate. Returns null if no graph was found.</summary>
public NavGraph FindGraph (System.Func<NavGraph, bool> predicate) {
if (graphs != null) {
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] != null && predicate(graphs[i])) {
return graphs[i];
}
}
}
return null;
}
/// <summary>Returns the first graph of type type found in the <see cref="graphs"/> array. Returns null if no graph was found.</summary>
public NavGraph FindGraphOfType (System.Type type) {
return FindGraph(graph => System.Type.Equals(graph.GetType(), type));
}
/// <summary>Returns the first graph which inherits from the type type. Returns null if no graph was found.</summary>
public NavGraph FindGraphWhichInheritsFrom (System.Type type) {
return FindGraph(graph => WindowsStoreCompatibility.GetTypeInfo(type).IsAssignableFrom(WindowsStoreCompatibility.GetTypeInfo(graph.GetType())));
}
/// <summary>
/// Loop through this function to get all graphs of type 'type'
/// <code>
/// foreach (GridGraph graph in AstarPath.data.FindGraphsOfType (typeof(GridGraph))) {
/// //Do something with the graph
/// }
/// </code>
/// See: AstarPath.RegisterSafeNodeUpdate
/// </summary>
public IEnumerable FindGraphsOfType (System.Type type) {
if (graphs == null) yield break;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] != null && System.Type.Equals(graphs[i].GetType(), type)) {
yield return graphs[i];
}
}
}
/// <summary>
/// All graphs which implements the UpdateableGraph interface
/// <code> foreach (IUpdatableGraph graph in AstarPath.data.GetUpdateableGraphs ()) {
/// //Do something with the graph
/// } </code>
/// See: AstarPath.AddWorkItem
/// See: Pathfinding.IUpdatableGraph
/// </summary>
public IEnumerable GetUpdateableGraphs () {
if (graphs == null) yield break;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] is IUpdatableGraph) {
yield return graphs[i];
}
}
}
/// <summary>
/// All graphs which implements the UpdateableGraph interface
/// <code> foreach (IRaycastableGraph graph in AstarPath.data.GetRaycastableGraphs ()) {
/// //Do something with the graph
/// } </code>
/// See: Pathfinding.IRaycastableGraph
/// Deprecated: Deprecated because it is not used by the package internally and the use cases are few. Iterate through the <see cref="graphs"/> array instead.
/// </summary>
[System.Obsolete("Obsolete because it is not used by the package internally and the use cases are few. Iterate through the graphs array instead.")]
public IEnumerable GetRaycastableGraphs () {
if (graphs == null) yield break;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] is IRaycastableGraph) {
yield return graphs[i];
}
}
}
/// <summary>Gets the index of the NavGraph in the <see cref="graphs"/> array</summary>
public int GetGraphIndex (NavGraph graph) {
if (graph == null) throw new System.ArgumentNullException("graph");
var index = -1;
if (graphs != null) {
index = System.Array.IndexOf(graphs, graph);
if (index == -1) Debug.LogError("Graph doesn't exist");
}
return index;
}
#endregion
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 38d211caa07cb44ef886481aa1cf755c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 960fd9020b1f74f939fee737c3c0f491
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}

View File

@@ -0,0 +1,16 @@
fileFormatVersion: 2
guid: 78396926cbbfc4ac3b48fc5fc34a87d1
labels:
- Pathfinder
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences:
- gizmoSurfaceMaterial: {fileID: 2100000, guid: 5ce51318bbfb1466188b929a68a6bd3a,
type: 2}
- gizmoLineMaterial: {fileID: 2100000, guid: 91035448860ba4e708919485c73f7edc, type: 2}
executionOrder: -10000
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,398 @@
using UnityEngine;
namespace Pathfinding {
[AddComponentMenu("Pathfinding/GraphUpdateScene")]
/// <summary>
/// Helper class for easily updating graphs.
///
/// The GraphUpdateScene component is really easy to use. Create a new empty GameObject and add the component to it, it can be found in Components-->Pathfinding-->GraphUpdateScene.\n
/// When you have added the component, you should see something like the image below.
/// [Open online documentation to see images]
/// The region which the component will affect is defined by creating a polygon in the scene.
/// If you make sure you have the Position tool enabled (top-left corner of the Unity window) you can shift+click in the scene view to add more points to the polygon.
/// You can remove points using shift+alt+click.
/// By clicking on the points you can bring up a positioning tool. You can also open the "points" array in the inspector to set each point's coordinates manually.
/// [Open online documentation to see images]
/// In the inspector there are a number of variables. The first one is named "Convex", it sets if the convex hull of the points should be calculated or if the polygon should be used as-is.
/// Using the convex hull is faster when applying the changes to the graph, but with a non-convex polygon you can specify more complicated areas.\n
/// The next two variables, called "Apply On Start" and "Apply On Scan" determine when to apply the changes. If the object is in the scene from the beginning, both can be left on, it doesn't
/// matter since the graph is also scanned at start. However if you instantiate it later in the game, you can make it apply it's setting directly, or wait until the next scan (if any).
/// If the graph is rescanned, all GraphUpdateScene components which have the Apply On Scan variable toggled will apply their settings again to the graph since rescanning clears all previous changes.\n
/// You can also make it apply it's changes using scripting.
/// <code> GetComponent<GraphUpdateScene>().Apply (); </code>
/// The above code will make it apply its changes to the graph (assuming a GraphUpdateScene component is attached to the same GameObject).
///
/// Next there is "Modify Walkability" and "Set Walkability" (which appears when "Modify Walkability" is toggled).
/// If Modify Walkability is set, then all nodes inside the area will either be set to walkable or unwalkable depending on the value of the "Set Walkability" variable.
///
/// Penalty can also be applied to the nodes. A higher penalty (aka weight) makes the nodes harder to traverse so it will try to avoid those areas.
///
/// The tagging variables can be read more about on this page: tags (view in online documentation for working links) "Working with tags".
///
/// Note: The Y (up) axis of the transform that this component is attached to should be in the same direction as the up direction of the graph.
/// So if you for example have a grid in the XY plane then the transform should have the rotation (-90,0,0).
/// </summary>
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_graph_update_scene.php")]
public class GraphUpdateScene : GraphModifier {
/// <summary>Points which define the region to update</summary>
public Vector3[] points;
/// <summary>Private cached convex hull of the <see cref="points"/></summary>
private Vector3[] convexPoints;
/// <summary>
/// Use the convex hull of the points instead of the original polygon.
///
/// See: https://en.wikipedia.org/wiki/Convex_hull
/// </summary>
public bool convex = true;
/// <summary>
/// Minumum height of the bounds of the resulting Graph Update Object.
/// Useful when all points are laid out on a plane but you still need a bounds with a height greater than zero since a
/// zero height graph update object would usually result in no nodes being updated.
/// </summary>
public float minBoundsHeight = 1;
/// <summary>
/// Penalty to add to nodes.
/// Usually you need quite large values, at least 1000-10000. A higher penalty means that agents will try to avoid those nodes more.
///
/// Be careful when setting negative values since if a node gets a negative penalty it will underflow and instead get
/// really large. In most cases a warning will be logged if that happens.
///
/// See: tags (view in online documentation for working links) for another way of applying penalties.
/// </summary>
public int penaltyDelta;
/// <summary>If true, then all affected nodes will be made walkable or unwalkable according to <see cref="setWalkability"/></summary>
public bool modifyWalkability;
/// <summary>Nodes will be made walkable or unwalkable according to this value if <see cref="modifyWalkability"/> is true</summary>
public bool setWalkability;
/// <summary>Apply this graph update object on start</summary>
public bool applyOnStart = true;
/// <summary>Apply this graph update object whenever a graph is rescanned</summary>
public bool applyOnScan = true;
/// <summary>
/// Update node's walkability and connectivity using physics functions.
/// For grid graphs, this will update the node's position and walkability exactly like when doing a scan of the graph.
/// If enabled for grid graphs, <see cref="modifyWalkability"/> will be ignored.
///
/// For Point Graphs, this will recalculate all connections which passes through the bounds of the resulting Graph Update Object
/// using raycasts (if enabled).
/// </summary>
public bool updatePhysics;
/// <summary>\copydoc Pathfinding::GraphUpdateObject::resetPenaltyOnPhysics</summary>
public bool resetPenaltyOnPhysics = true;
/// <summary>\copydoc Pathfinding::GraphUpdateObject::updateErosion</summary>
public bool updateErosion = true;
/// <summary>
/// Should the tags of the nodes be modified.
/// If enabled, set all nodes' tags to <see cref="setTag"/>
/// </summary>
public bool modifyTag;
/// <summary>If <see cref="modifyTag"/> is enabled, set all nodes' tags to this value</summary>
public int setTag;
/// <summary>Emulates behavior from before version 4.0</summary>
[HideInInspector]
public bool legacyMode = false;
/// <summary>
/// Private cached inversion of <see cref="setTag"/>.
/// Used for InvertSettings()
/// </summary>
private int setTagInvert;
/// <summary>
/// Has apply been called yet.
/// Used to prevent applying twice when both applyOnScan and applyOnStart are enabled
/// </summary>
private bool firstApplied;
[SerializeField]
private int serializedVersion = 0;
/// <summary>
/// Use world space for coordinates.
/// If true, the shape will not follow when moving around the transform.
///
/// See: <see cref="ToggleUseWorldSpace"/>
/// </summary>
[SerializeField]
[UnityEngine.Serialization.FormerlySerializedAs("useWorldSpace")]
private bool legacyUseWorldSpace;
/// <summary>Do some stuff at start</summary>
public void Start () {
if (!Application.isPlaying) return;
// If firstApplied is true, that means the graph was scanned during Awake.
// So we shouldn't apply it again because then we would end up applying it two times
if (!firstApplied && applyOnStart) {
Apply();
}
}
public override void OnPostScan () {
if (applyOnScan) Apply();
}
/// <summary>
/// Inverts all invertable settings for this GUS.
/// Namely: penalty delta, walkability, tags.
///
/// Penalty delta will be changed to negative penalty delta.\n
/// <see cref="setWalkability"/> will be inverted.\n
/// <see cref="setTag"/> will be stored in a private variable, and the new value will be 0. When calling this function again, the saved
/// value will be the new value.
///
/// Calling this function an even number of times without changing any settings in between will be identical to no change in settings.
/// </summary>
public virtual void InvertSettings () {
setWalkability = !setWalkability;
penaltyDelta = -penaltyDelta;
if (setTagInvert == 0) {
setTagInvert = setTag;
setTag = 0;
} else {
setTag = setTagInvert;
setTagInvert = 0;
}
}
/// <summary>
/// Recalculate convex hull.
/// Will not do anything if <see cref="convex"/> is disabled.
/// </summary>
public void RecalcConvex () {
convexPoints = convex ? Polygon.ConvexHullXZ(points) : null;
}
/// <summary>
/// Switches between using world space and using local space.
/// Deprecated: World space can no longer be used as it does not work well with rotated graphs. Use transform.InverseTransformPoint to transform points to local space.
/// </summary>
[System.ObsoleteAttribute("World space can no longer be used as it does not work well with rotated graphs. Use transform.InverseTransformPoint to transform points to local space.", true)]
void ToggleUseWorldSpace () {
}
/// <summary>
/// Lock all points to a specific Y value.
/// Deprecated: The Y coordinate is no longer important. Use the position of the object instead.
/// </summary>
[System.ObsoleteAttribute("The Y coordinate is no longer important. Use the position of the object instead", true)]
public void LockToY () {
}
/// <summary>
/// Calculates the bounds for this component.
/// This is a relatively expensive operation, it needs to go through all points and
/// run matrix multiplications.
/// </summary>
public Bounds GetBounds () {
if (points == null || points.Length == 0) {
Bounds bounds;
var coll = GetComponent<Collider>();
var coll2D = GetComponent<Collider2D>();
var rend = GetComponent<Renderer>();
if (coll != null) bounds = coll.bounds;
else if (coll2D != null) {
bounds = coll2D.bounds;
bounds.size = new Vector3(bounds.size.x, bounds.size.y, Mathf.Max(bounds.size.z, 1f));
} else if (rend != null) {
bounds = rend.bounds;
} else {
return new Bounds(Vector3.zero, Vector3.zero);
}
if (legacyMode && bounds.size.y < minBoundsHeight) bounds.size = new Vector3(bounds.size.x, minBoundsHeight, bounds.size.z);
return bounds;
} else {
return GraphUpdateShape.GetBounds(convex ? convexPoints : points, legacyMode && legacyUseWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix, minBoundsHeight);
}
}
/// <summary>
/// Updates graphs with a created GUO.
/// Creates a Pathfinding.GraphUpdateObject with a Pathfinding.GraphUpdateShape
/// representing the polygon of this object and update all graphs using AstarPath.UpdateGraphs.
/// This will not update graphs immediately. See AstarPath.UpdateGraph for more info.
/// </summary>
public void Apply () {
if (AstarPath.active == null) {
Debug.LogError("There is no AstarPath object in the scene", this);
return;
}
GraphUpdateObject guo;
if (points == null || points.Length == 0) {
var polygonCollider = GetComponent<PolygonCollider2D>();
if (polygonCollider != null) {
var points2D = polygonCollider.points;
Vector3[] pts = new Vector3[points2D.Length];
for (int i = 0; i < pts.Length; i++) {
var p = points2D[i] + polygonCollider.offset;
pts[i] = new Vector3(p.x, 0, p.y);
}
var mat = transform.localToWorldMatrix * Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(-90, 0, 0), Vector3.one);
var shape = new GraphUpdateShape(pts, convex, mat, minBoundsHeight);
guo = new GraphUpdateObject(GetBounds());
guo.shape = shape;
} else {
var bounds = GetBounds();
if (bounds.center == Vector3.zero && bounds.size == Vector3.zero) {
Debug.LogError("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached", this);
return;
}
guo = new GraphUpdateObject(bounds);
}
} else {
GraphUpdateShape shape;
if (legacyMode && !legacyUseWorldSpace) {
// Used for compatibility with older versions
var worldPoints = new Vector3[points.Length];
for (int i = 0; i < points.Length; i++) worldPoints[i] = transform.TransformPoint(points[i]);
shape = new GraphUpdateShape(worldPoints, convex, Matrix4x4.identity, minBoundsHeight);
} else {
shape = new GraphUpdateShape(points, convex, legacyMode && legacyUseWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix, minBoundsHeight);
}
var bounds = shape.GetBounds();
guo = new GraphUpdateObject(bounds);
guo.shape = shape;
}
firstApplied = true;
guo.modifyWalkability = modifyWalkability;
guo.setWalkability = setWalkability;
guo.addPenalty = penaltyDelta;
guo.updatePhysics = updatePhysics;
guo.updateErosion = updateErosion;
guo.resetPenaltyOnPhysics = resetPenaltyOnPhysics;
guo.modifyTag = modifyTag;
guo.setTag = setTag;
AstarPath.active.UpdateGraphs(guo);
}
/// <summary>Draws some gizmos</summary>
void OnDrawGizmos () {
OnDrawGizmos(false);
}
/// <summary>Draws some gizmos</summary>
void OnDrawGizmosSelected () {
OnDrawGizmos(true);
}
/// <summary>Draws some gizmos</summary>
void OnDrawGizmos (bool selected) {
Color c = selected ? new Color(227/255f, 61/255f, 22/255f, 1.0f) : new Color(227/255f, 61/255f, 22/255f, 0.9f);
if (selected) {
Gizmos.color = Color.Lerp(c, new Color(1, 1, 1, 0.2f), 0.9f);
Bounds b = GetBounds();
Gizmos.DrawCube(b.center, b.size);
Gizmos.DrawWireCube(b.center, b.size);
}
if (points == null) return;
if (convex) c.a *= 0.5f;
Gizmos.color = c;
Matrix4x4 matrix = legacyMode && legacyUseWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix;
if (convex) {
c.r -= 0.1f;
c.g -= 0.2f;
c.b -= 0.1f;
Gizmos.color = c;
}
if (selected || !convex) {
for (int i = 0; i < points.Length; i++) {
Gizmos.DrawLine(matrix.MultiplyPoint3x4(points[i]), matrix.MultiplyPoint3x4(points[(i+1)%points.Length]));
}
}
if (convex) {
if (convexPoints == null) RecalcConvex();
Gizmos.color = selected ? new Color(227/255f, 61/255f, 22/255f, 1.0f) : new Color(227/255f, 61/255f, 22/255f, 0.9f);
for (int i = 0; i < convexPoints.Length; i++) {
Gizmos.DrawLine(matrix.MultiplyPoint3x4(convexPoints[i]), matrix.MultiplyPoint3x4(convexPoints[(i+1)%convexPoints.Length]));
}
}
// Draw the full 3D shape
var pts = convex ? convexPoints : points;
if (selected && pts != null && pts.Length > 0) {
Gizmos.color = new Color(1, 1, 1, 0.2f);
float miny = pts[0].y, maxy = pts[0].y;
for (int i = 0; i < pts.Length; i++) {
miny = Mathf.Min(miny, pts[i].y);
maxy = Mathf.Max(maxy, pts[i].y);
}
var extraHeight = Mathf.Max(minBoundsHeight - (maxy - miny), 0) * 0.5f;
miny -= extraHeight;
maxy += extraHeight;
for (int i = 0; i < pts.Length; i++) {
var next = (i+1) % pts.Length;
var p1 = matrix.MultiplyPoint3x4(pts[i] + Vector3.up*(miny - pts[i].y));
var p2 = matrix.MultiplyPoint3x4(pts[i] + Vector3.up*(maxy - pts[i].y));
var p1n = matrix.MultiplyPoint3x4(pts[next] + Vector3.up*(miny - pts[next].y));
var p2n = matrix.MultiplyPoint3x4(pts[next] + Vector3.up*(maxy - pts[next].y));
Gizmos.DrawLine(p1, p2);
Gizmos.DrawLine(p1, p1n);
Gizmos.DrawLine(p2, p2n);
}
}
}
/// <summary>
/// Disables legacy mode if it is enabled.
/// Legacy mode is automatically enabled for components when upgrading from an earlier version than 3.8.6.
/// </summary>
public void DisableLegacyMode () {
if (legacyMode) {
legacyMode = false;
if (legacyUseWorldSpace) {
legacyUseWorldSpace = false;
for (int i = 0; i < points.Length; i++) {
points[i] = transform.InverseTransformPoint(points[i]);
}
RecalcConvex();
}
}
}
protected override void Awake () {
if (serializedVersion == 0) {
// Use the old behavior if some points are already set
if (points != null && points.Length > 0) legacyMode = true;
serializedVersion = 1;
}
base.Awake();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: efee954c69f0d421086729bb8df1137f
timeCreated: 1490044676
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: -221
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,143 @@
using UnityEngine;
namespace Pathfinding {
/// <summary>
/// Defines a shape for a Pathfinding.GraphUpdateObject.
/// The shape consists of a number of points which it can either calculate the convex hull of or use as a polygon directly.
///
/// A shape is essentially a 2D shape however it can be rotated arbitrarily.
/// When a matrix and a list of points is specified in the constructor the matrix decides what direction
/// is the 'up' direction. When checking if a point is contained in the shape, the point will be projected down
/// on a plane where the 'up' direction is the normal and then it will check if the shape contains the point.
///
/// See: Pathfinding.GraphUpdateObject.shape
/// </summary>
public class GraphUpdateShape {
Vector3[] _points;
Vector3[] _convexPoints;
bool _convex;
Vector3 right = Vector3.right;
Vector3 forward = Vector3.forward;
Vector3 up = Vector3.up;
Vector3 origin;
public float minimumHeight;
/// <summary>
/// Gets or sets the points of the polygon in the shape.
/// These points should be specified in clockwise order.
/// Will automatically calculate the convex hull if <see cref="convex"/> is set to true
/// </summary>
public Vector3[] points {
get {
return _points;
}
set {
_points = value;
if (convex) CalculateConvexHull();
}
}
/// <summary>
/// Sets if the convex hull of the points should be calculated.
/// Convex hulls are faster but non-convex hulls can be used to specify more complicated shapes.
/// </summary>
public bool convex {
get {
return _convex;
}
set {
if (_convex != value && value) {
CalculateConvexHull();
}
_convex = value;
}
}
public GraphUpdateShape () {
}
/// <summary>
/// Construct a shape.
/// See: <see cref="convex"/>
/// </summary>
/// <param name="points">Contour of the shape in local space with respect to the matrix (i.e the shape should be in the XZ plane, the Y coordinate will only affect the bounds)</param>
/// <param name="convex">If true, the convex hull of the points will be calculated.</param>
/// <param name="matrix">local to world space matrix for the points. The matrix determines the up direction of the shape.</param>
/// <param name="minimumHeight">If the points would be in the XZ plane only, the shape would not have a height and then it might not
/// include any points inside it (as testing for inclusion is done in 3D space when updating graphs). This ensures
/// that the shape has at least the minimum height (in the up direction that the matrix specifies).</param>
public GraphUpdateShape (Vector3[] points, bool convex, Matrix4x4 matrix, float minimumHeight) {
this.convex = convex;
this.points = points;
origin = matrix.MultiplyPoint3x4(Vector3.zero);
right = matrix.MultiplyPoint3x4(Vector3.right) - origin;
up = matrix.MultiplyPoint3x4(Vector3.up) - origin;
forward = matrix.MultiplyPoint3x4(Vector3.forward) - origin;
this.minimumHeight = minimumHeight;
}
void CalculateConvexHull () {
_convexPoints = points != null? Polygon.ConvexHullXZ(points) : null;
}
/// <summary>World space bounding box of this shape</summary>
public Bounds GetBounds () {
return GetBounds(convex ? _convexPoints : points, right, up, forward, origin, minimumHeight);
}
public static Bounds GetBounds (Vector3[] points, Matrix4x4 matrix, float minimumHeight) {
var origin = matrix.MultiplyPoint3x4(Vector3.zero);
var right = matrix.MultiplyPoint3x4(Vector3.right) - origin;
var up = matrix.MultiplyPoint3x4(Vector3.up) - origin;
var forward = matrix.MultiplyPoint3x4(Vector3.forward) - origin;
return GetBounds(points, right, up, forward, origin, minimumHeight);
}
static Bounds GetBounds (Vector3[] points, Vector3 right, Vector3 up, Vector3 forward, Vector3 origin, float minimumHeight) {
if (points == null || points.Length == 0) return new Bounds();
float miny = points[0].y, maxy = points[0].y;
for (int i = 0; i < points.Length; i++) {
miny = Mathf.Min(miny, points[i].y);
maxy = Mathf.Max(maxy, points[i].y);
}
var extraHeight = Mathf.Max(minimumHeight - (maxy - miny), 0) * 0.5f;
miny -= extraHeight;
maxy += extraHeight;
Vector3 min = right * points[0].x + up * points[0].y + forward * points[0].z;
Vector3 max = min;
for (int i = 0; i < points.Length; i++) {
var p = right * points[i].x + forward * points[i].z;
var p1 = p + up * miny;
var p2 = p + up * maxy;
min = Vector3.Min(min, p1);
min = Vector3.Min(min, p2);
max = Vector3.Max(max, p1);
max = Vector3.Max(max, p2);
}
return new Bounds((min+max)*0.5F + origin, max-min);
}
public bool Contains (GraphNode node) {
return Contains((Vector3)node.position);
}
public bool Contains (Vector3 point) {
// Transform to local space (shape in the XZ plane)
point -= origin;
var localSpacePoint = new Vector3(Vector3.Dot(point, right)/right.sqrMagnitude, 0, Vector3.Dot(point, forward)/forward.sqrMagnitude);
if (convex) {
if (_convexPoints == null) return false;
for (int i = 0, j = _convexPoints.Length-1; i < _convexPoints.Length; j = i, i++) {
if (VectorMath.RightOrColinearXZ(_convexPoints[i], _convexPoints[j], localSpacePoint)) return false;
}
return true;
} else {
return _points != null && Polygon.ContainsPointXZ(_points, localSpacePoint);
}
}
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 1c31d3b0be14344e98aa458dc66c3a94
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: dfc976d61106d46b6a18ace94ffaea8d

View File

@@ -0,0 +1,122 @@
using UnityEngine;
using System.Collections.Generic;
namespace Pathfinding {
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_animation_link.php")]
public class AnimationLink : NodeLink2 {
public string clip;
public float animSpeed = 1;
public bool reverseAnim = true;
public GameObject referenceMesh;
public LinkClip[] sequence;
public string boneRoot = "bn_COG_Root";
[System.Serializable]
public class LinkClip {
public AnimationClip clip;
public Vector3 velocity;
public int loopCount = 1;
public string name {
get {
return clip != null ? clip.name : "";
}
}
}
static Transform SearchRec (Transform tr, string name) {
int childCount = tr.childCount;
for (int i = 0; i < childCount; i++) {
Transform ch = tr.GetChild(i);
if (ch.name == name) return ch;
else {
Transform rec = SearchRec(ch, name);
if (rec != null) return rec;
}
}
return null;
}
public void CalculateOffsets (List<Vector3> trace, out Vector3 endPosition) {
//Vector3 opos = transform.position;
endPosition = transform.position;
if (referenceMesh == null) return;
GameObject ob = GameObject.Instantiate(referenceMesh, transform.position, transform.rotation) as GameObject;
ob.hideFlags = HideFlags.HideAndDontSave;
Transform root = SearchRec(ob.transform, boneRoot);
if (root == null) throw new System.Exception("Could not find root transform");
Animation anim = ob.GetComponent<Animation>();
if (anim == null) anim = ob.AddComponent<Animation>();
for (int i = 0; i < sequence.Length; i++) {
anim.AddClip(sequence[i].clip, sequence[i].clip.name);
}
Vector3 prevOffset = Vector3.zero;
Vector3 position = transform.position;
Vector3 firstOffset = Vector3.zero;
for (int i = 0; i < sequence.Length; i++) {
LinkClip c = sequence[i];
if (c == null) {
endPosition = position;
return;
}
anim[c.clip.name].enabled = true;
anim[c.clip.name].weight = 1;
for (int repeat = 0; repeat < c.loopCount; repeat++) {
anim[c.clip.name].normalizedTime = 0;
anim.Sample();
Vector3 soffset = root.position - transform.position;
if (i > 0) {
position += prevOffset - soffset;
} else {
firstOffset = soffset;
}
for (int t = 0; t <= 20; t++) {
float tf = t/20.0f;
anim[c.clip.name].normalizedTime = tf;
anim.Sample();
Vector3 tmp = position + (root.position-transform.position) + c.velocity*tf*c.clip.length;
trace.Add(tmp);
}
position = position + c.velocity*1*c.clip.length;
anim[c.clip.name].normalizedTime = 1;
anim.Sample();
Vector3 eoffset = root.position - transform.position;
prevOffset = eoffset;
}
anim[c.clip.name].enabled = false;
anim[c.clip.name].weight = 0;
}
position += prevOffset - firstOffset;
GameObject.DestroyImmediate(ob);
endPosition = position;
}
public override void OnDrawGizmosSelected () {
base.OnDrawGizmosSelected();
List<Vector3> buffer = Pathfinding.Util.ListPool<Vector3>.Claim();
Vector3 endPosition = Vector3.zero;
CalculateOffsets(buffer, out endPosition);
Gizmos.color = Color.blue;
for (int i = 0; i < buffer.Count-1; i++) {
Gizmos.DrawLine(buffer[i], buffer[i+1]);
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d2e8b1fd6fa484fc29f8a26fb5e8662b
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,198 @@
#if !UNITY_EDITOR
// Extra optimizations when not running in the editor, but less error checking
#define ASTAR_OPTIMIZE_POOLING
#endif
using System;
using System.Collections.Generic;
namespace Pathfinding.Util {
/// <summary>
/// Lightweight Array Pool.
/// Handy class for pooling arrays of type T.
///
/// Usage:
/// - Claim a new array using <code> SomeClass[] foo = ArrayPool<SomeClass>.Claim (capacity); </code>
/// - Use it and do stuff with it
/// - Release it with <code> ArrayPool<SomeClass>.Release (foo); </code>
///
/// Warning: Arrays returned from the Claim method may contain arbitrary data.
/// You cannot rely on it being zeroed out.
///
/// After you have released a array, you should never use it again, if you do use it
/// your code may modify it at the same time as some other code is using it which
/// will likely lead to bad results.
///
/// \since Version 3.8.6
/// See: Pathfinding.Util.ListPool
/// </summary>
public static class ArrayPool<T> {
#if !ASTAR_NO_POOLING
/// <summary>
/// Maximum length of an array pooled using ClaimWithExactLength.
/// Arrays with lengths longer than this will silently not be pooled.
/// </summary>
const int MaximumExactArrayLength = 256;
/// <summary>
/// Internal pool.
/// The arrays in each bucket have lengths of 2^i
/// </summary>
static readonly Stack<T[]>[] pool = new Stack<T[]>[31];
static readonly Stack<T[]>[] exactPool = new Stack<T[]>[MaximumExactArrayLength+1];
#if !ASTAR_OPTIMIZE_POOLING
static readonly HashSet<T[]> inPool = new HashSet<T[]>();
#endif
#endif
/// <summary>
/// Returns an array with at least the specified length.
/// Warning: Returned arrays may contain arbitrary data.
/// You cannot rely on it being zeroed out.
/// </summary>
public static T[] Claim (int minimumLength) {
if (minimumLength <= 0) {
return ClaimWithExactLength(0);
}
int bucketIndex = 0;
while ((1 << bucketIndex) < minimumLength && bucketIndex < 30) {
bucketIndex++;
}
if (bucketIndex == 30)
throw new System.ArgumentException("Too high minimum length");
#if !ASTAR_NO_POOLING
lock (pool) {
if (pool[bucketIndex] == null) {
pool[bucketIndex] = new Stack<T[]>();
}
if (pool[bucketIndex].Count > 0) {
var array = pool[bucketIndex].Pop();
#if !ASTAR_OPTIMIZE_POOLING
inPool.Remove(array);
#endif
return array;
}
}
#endif
return new T[1 << bucketIndex];
}
/// <summary>
/// Returns an array with the specified length.
/// Use with caution as pooling too many arrays with different lengths that
/// are rarely being reused will lead to an effective memory leak.
///
/// Use <see cref="Claim"/> if you just need an array that is at least as large as some value.
///
/// Warning: Returned arrays may contain arbitrary data.
/// You cannot rely on it being zeroed out.
/// </summary>
public static T[] ClaimWithExactLength (int length) {
#if !ASTAR_NO_POOLING
bool isPowerOfTwo = length != 0 && (length & (length - 1)) == 0;
if (isPowerOfTwo) {
// Will return the correct array length
return Claim(length);
}
if (length <= MaximumExactArrayLength) {
lock (pool) {
Stack<T[]> stack = exactPool[length];
if (stack != null && stack.Count > 0) {
var array = stack.Pop();
#if !ASTAR_OPTIMIZE_POOLING
inPool.Remove(array);
#endif
return array;
}
}
}
#endif
return new T[length];
}
/// <summary>
/// Pool an array.
/// If the array was got using the <see cref="ClaimWithExactLength"/> method then the allowNonPowerOfTwo parameter must be set to true.
/// The parameter exists to make sure that non power of two arrays are not pooled unintentionally which could lead to memory leaks.
/// </summary>
public static void Release (ref T[] array, bool allowNonPowerOfTwo = false) {
if (array == null) return;
if (array.GetType() != typeof(T[])) {
throw new System.ArgumentException("Expected array type " + typeof(T[]).Name + " but found " + array.GetType().Name + "\nAre you using the correct generic class?\n");
}
#if !ASTAR_NO_POOLING
bool isPowerOfTwo = array.Length != 0 && (array.Length & (array.Length - 1)) == 0;
if (!isPowerOfTwo && !allowNonPowerOfTwo && array.Length != 0) throw new System.ArgumentException("Length is not a power of 2");
lock (pool) {
#if !ASTAR_OPTIMIZE_POOLING
if (!inPool.Add(array)) {
throw new InvalidOperationException("You are trying to pool an array twice. Please make sure that you only pool it once.");
}
#endif
if (isPowerOfTwo) {
int bucketIndex = 0;
while ((1 << bucketIndex) < array.Length && bucketIndex < 30) {
bucketIndex++;
}
if (pool[bucketIndex] == null) {
pool[bucketIndex] = new Stack<T[]>();
}
pool[bucketIndex].Push(array);
} else if (array.Length <= MaximumExactArrayLength) {
Stack<T[]> stack = exactPool[array.Length];
if (stack == null) stack = exactPool[array.Length] = new Stack<T[]>();
stack.Push(array);
}
}
#endif
array = null;
}
}
/// <summary>Extension methods for List<T></summary>
public static class ListExtensions {
/// <summary>
/// Identical to ToArray but it uses ArrayPool<T> to avoid allocations if possible.
///
/// Use with caution as pooling too many arrays with different lengths that
/// are rarely being reused will lead to an effective memory leak.
/// </summary>
public static T[] ToArrayFromPool<T>(this List<T> list) {
var arr = ArrayPool<T>.ClaimWithExactLength(list.Count);
for (int i = 0; i < arr.Length; i++) {
arr[i] = list[i];
}
return arr;
}
/// <summary>
/// Clear a list faster than List<T>.Clear.
/// It turns out that the List<T>.Clear method will clear all elements in the underlaying array
/// not just the ones up to Count. If the list only has a few elements, but the capacity
/// is huge, this can cause performance problems. Using the RemoveRange method to remove
/// all elements in the list does not have this problem, however it is implemented in a
/// stupid way, so it will clear the elements twice (completely unnecessarily) so it will
/// only be faster than using the Clear method if the number of elements in the list is
/// less than half of the capacity of the list.
///
/// Hopefully this method can be removed when Unity upgrades to a newer version of Mono.
/// </summary>
public static void ClearFast<T>(this List<T> list) {
if (list.Count*2 < list.Capacity) {
list.RemoveRange(0, list.Count);
} else {
list.Clear();
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 787a564bf2d894ee09284b775074864c
timeCreated: 1470483941
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,337 @@
//#define ProfileAstar
using UnityEngine;
using System.Text;
namespace Pathfinding {
[AddComponentMenu("Pathfinding/Pathfinding Debugger")]
[ExecuteInEditMode]
/// <summary>
/// Debugger for the A* Pathfinding Project.
/// This class can be used to profile different parts of the pathfinding system
/// and the whole game as well to some extent.
///
/// Clarification of the labels shown when enabled.
/// All memory related things profiles <b>the whole game</b> not just the A* Pathfinding System.\n
/// - Currently allocated: memory the GC (garbage collector) says the application has allocated right now.
/// - Peak allocated: maximum measured value of the above.
/// - Last collect peak: the last peak of 'currently allocated'.
/// - Allocation rate: how much the 'currently allocated' value increases per second. This value is not as reliable as you can think
/// it is often very random probably depending on how the GC thinks this application is using memory.
/// - Collection frequency: how often the GC is called. Again, the GC might decide it is better with many small collections
/// or with a few large collections. So you cannot really trust this variable much.
/// - Last collect fps: FPS during the last garbage collection, the GC will lower the fps a lot.
///
/// - FPS: current FPS (not updated every frame for readability)
/// - Lowest FPS (last x): As the label says, the lowest fps of the last x frames.
///
/// - Size: Size of the path pool.
/// - Total created: Number of paths of that type which has been created. Pooled paths are not counted twice.
/// If this value just keeps on growing and growing without an apparent stop, you are are either not pooling any paths
/// or you have missed to pool some path somewhere in your code.
///
/// See: pooling
///
/// TODO: Add field showing how many graph updates are being done right now
/// </summary>
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_astar_debugger.php")]
public class AstarDebugger : VersionedMonoBehaviour {
public int yOffset = 5;
public bool show = true;
public bool showInEditor = false;
public bool showFPS = false;
public bool showPathProfile = false;
public bool showMemProfile = false;
public bool showGraph = false;
public int graphBufferSize = 200;
/// <summary>
/// Font to use.
/// A monospaced font is the best
/// </summary>
public Font font = null;
public int fontSize = 12;
StringBuilder text = new StringBuilder();
string cachedText;
float lastUpdate = -999;
private GraphPoint[] graph;
struct GraphPoint {
public float fps, memory;
public bool collectEvent;
}
private float delayedDeltaTime = 1;
private float lastCollect = 0;
private float lastCollectNum = 0;
private float delta = 0;
private float lastDeltaTime = 0;
private int allocRate = 0;
private int lastAllocMemory = 0;
private float lastAllocSet = -9999;
private int allocMem = 0;
private int collectAlloc = 0;
private int peakAlloc = 0;
private int fpsDropCounterSize = 200;
private float[] fpsDrops;
private Rect boxRect;
private GUIStyle style;
private Camera cam;
float graphWidth = 100;
float graphHeight = 100;
float graphOffset = 50;
public void Start () {
useGUILayout = false;
fpsDrops = new float[fpsDropCounterSize];
cam = GetComponent<Camera>();
if (cam == null) {
cam = Camera.main;
}
graph = new GraphPoint[graphBufferSize];
if (Time.unscaledDeltaTime > 0) {
for (int i = 0; i < fpsDrops.Length; i++) {
fpsDrops[i] = 1F / Time.unscaledDeltaTime;
}
}
}
int maxVecPool = 0;
int maxNodePool = 0;
PathTypeDebug[] debugTypes = new PathTypeDebug[] {
new PathTypeDebug("ABPath", () => PathPool.GetSize(typeof(ABPath)), () => PathPool.GetTotalCreated(typeof(ABPath)))
};
struct PathTypeDebug {
string name;
System.Func<int> getSize;
System.Func<int> getTotalCreated;
public PathTypeDebug (string name, System.Func<int> getSize, System.Func<int> getTotalCreated) {
this.name = name;
this.getSize = getSize;
this.getTotalCreated = getTotalCreated;
}
public void Print (StringBuilder text) {
int totCreated = getTotalCreated();
if (totCreated > 0) {
text.Append("\n").Append((" " + name).PadRight(25)).Append(getSize()).Append("/").Append(totCreated);
}
}
}
public void LateUpdate () {
if (!show || (!Application.isPlaying && !showInEditor)) return;
if (Time.unscaledDeltaTime <= 0.0001f)
return;
int collCount = System.GC.CollectionCount(0);
if (lastCollectNum != collCount) {
lastCollectNum = collCount;
delta = Time.realtimeSinceStartup-lastCollect;
lastCollect = Time.realtimeSinceStartup;
lastDeltaTime = Time.unscaledDeltaTime;
collectAlloc = allocMem;
}
allocMem = (int)System.GC.GetTotalMemory(false);
bool collectEvent = allocMem < peakAlloc;
peakAlloc = !collectEvent ? allocMem : peakAlloc;
if (Time.realtimeSinceStartup - lastAllocSet > 0.3F || !Application.isPlaying) {
int diff = allocMem - lastAllocMemory;
lastAllocMemory = allocMem;
lastAllocSet = Time.realtimeSinceStartup;
delayedDeltaTime = Time.unscaledDeltaTime;
if (diff >= 0) {
allocRate = diff;
}
}
if (Application.isPlaying) {
fpsDrops[Time.frameCount % fpsDrops.Length] = Time.unscaledDeltaTime > 0.00001f ? 1F / Time.unscaledDeltaTime : 0;
int graphIndex = Time.frameCount % graph.Length;
graph[graphIndex].fps = Time.unscaledDeltaTime < 0.00001f ? 1F / Time.unscaledDeltaTime : 0;
graph[graphIndex].collectEvent = collectEvent;
graph[graphIndex].memory = allocMem;
}
if (Application.isPlaying && cam != null && showGraph) {
graphWidth = cam.pixelWidth*0.8f;
float minMem = float.PositiveInfinity, maxMem = 0, minFPS = float.PositiveInfinity, maxFPS = 0;
for (int i = 0; i < graph.Length; i++) {
minMem = Mathf.Min(graph[i].memory, minMem);
maxMem = Mathf.Max(graph[i].memory, maxMem);
minFPS = Mathf.Min(graph[i].fps, minFPS);
maxFPS = Mathf.Max(graph[i].fps, maxFPS);
}
int currentGraphIndex = Time.frameCount % graph.Length;
Matrix4x4 m = Matrix4x4.TRS(new Vector3((cam.pixelWidth - graphWidth)/2f, graphOffset, 1), Quaternion.identity, new Vector3(graphWidth, graphHeight, 1));
for (int i = 0; i < graph.Length-1; i++) {
if (i == currentGraphIndex) continue;
DrawGraphLine(i, m, i/(float)graph.Length, (i+1)/(float)graph.Length, Mathf.InverseLerp(minMem, maxMem, graph[i].memory), Mathf.InverseLerp(minMem, maxMem, graph[i+1].memory), Color.blue);
DrawGraphLine(i, m, i/(float)graph.Length, (i+1)/(float)graph.Length, Mathf.InverseLerp(minFPS, maxFPS, graph[i].fps), Mathf.InverseLerp(minFPS, maxFPS, graph[i+1].fps), Color.green);
}
}
}
void DrawGraphLine (int index, Matrix4x4 m, float x1, float x2, float y1, float y2, Color color) {
Debug.DrawLine(cam.ScreenToWorldPoint(m.MultiplyPoint3x4(new Vector3(x1, y1))), cam.ScreenToWorldPoint(m.MultiplyPoint3x4(new Vector3(x2, y2))), color);
}
public void OnGUI () {
if (!show || (!Application.isPlaying && !showInEditor)) return;
if (style == null) {
style = new GUIStyle();
style.normal.textColor = Color.white;
style.padding = new RectOffset(5, 5, 5, 5);
}
if (Time.realtimeSinceStartup - lastUpdate > 0.5f || cachedText == null || !Application.isPlaying) {
lastUpdate = Time.realtimeSinceStartup;
boxRect = new Rect(5, yOffset, 310, 40);
text.Length = 0;
text.AppendLine("A* Pathfinding Project Debugger");
text.Append("A* Version: ").Append(AstarPath.Version.ToString());
if (showMemProfile) {
boxRect.height += 200;
text.AppendLine();
text.AppendLine();
text.Append("Currently allocated".PadRight(25));
text.Append((allocMem/1000000F).ToString("0.0 MB"));
text.AppendLine();
text.Append("Peak allocated".PadRight(25));
text.Append((peakAlloc/1000000F).ToString("0.0 MB")).AppendLine();
text.Append("Last collect peak".PadRight(25));
text.Append((collectAlloc/1000000F).ToString("0.0 MB")).AppendLine();
text.Append("Allocation rate".PadRight(25));
text.Append((allocRate/1000000F).ToString("0.0 MB")).AppendLine();
text.Append("Collection frequency".PadRight(25));
text.Append(delta.ToString("0.00"));
text.Append("s\n");
text.Append("Last collect fps".PadRight(25));
text.Append((1F/lastDeltaTime).ToString("0.0 fps"));
text.Append(" (");
text.Append(lastDeltaTime.ToString("0.000 s"));
text.Append(")");
}
if (showFPS) {
text.AppendLine();
text.AppendLine();
var delayedFPS = delayedDeltaTime > 0.00001f ? 1F/delayedDeltaTime : 0;
text.Append("FPS".PadRight(25)).Append(delayedFPS.ToString("0.0 fps"));
float minFps = Mathf.Infinity;
for (int i = 0; i < fpsDrops.Length; i++) if (fpsDrops[i] < minFps) minFps = fpsDrops[i];
text.AppendLine();
text.Append(("Lowest fps (last " + fpsDrops.Length + ")").PadRight(25)).Append(minFps.ToString("0.0"));
}
if (showPathProfile) {
AstarPath astar = AstarPath.active;
text.AppendLine();
if (astar == null) {
text.Append("\nNo AstarPath Object In The Scene");
} else {
#if ProfileAstar
double searchSpeed = (double)AstarPath.TotalSearchedNodes*10000 / (double)AstarPath.TotalSearchTime;
text.Append("\nSearch Speed (nodes/ms) ").Append(searchSpeed.ToString("0")).Append(" ("+AstarPath.TotalSearchedNodes+" / ").Append(((double)AstarPath.TotalSearchTime/10000F).ToString("0")+")");
#endif
if (Pathfinding.Util.ListPool<Vector3>.GetSize() > maxVecPool) maxVecPool = Pathfinding.Util.ListPool<Vector3>.GetSize();
if (Pathfinding.Util.ListPool<Pathfinding.GraphNode>.GetSize() > maxNodePool) maxNodePool = Pathfinding.Util.ListPool<Pathfinding.GraphNode>.GetSize();
text.Append("\nPool Sizes (size/total created)");
for (int i = 0; i < debugTypes.Length; i++) {
debugTypes[i].Print(text);
}
}
}
cachedText = text.ToString();
}
if (font != null) {
style.font = font;
style.fontSize = fontSize;
}
boxRect.height = style.CalcHeight(new GUIContent(cachedText), boxRect.width);
GUI.Box(boxRect, "");
GUI.Label(boxRect, cachedText, style);
if (showGraph) {
float minMem = float.PositiveInfinity, maxMem = 0, minFPS = float.PositiveInfinity, maxFPS = 0;
for (int i = 0; i < graph.Length; i++) {
minMem = Mathf.Min(graph[i].memory, minMem);
maxMem = Mathf.Max(graph[i].memory, maxMem);
minFPS = Mathf.Min(graph[i].fps, minFPS);
maxFPS = Mathf.Max(graph[i].fps, maxFPS);
}
float line;
GUI.color = Color.blue;
// Round to nearest x.x MB
line = Mathf.RoundToInt(maxMem/(100.0f*1000));
GUI.Label(new Rect(5, Screen.height - AstarMath.MapTo(minMem, maxMem, 0 + graphOffset, graphHeight + graphOffset, line*1000*100) - 10, 100, 20), (line/10.0f).ToString("0.0 MB"));
line = Mathf.Round(minMem/(100.0f*1000));
GUI.Label(new Rect(5, Screen.height - AstarMath.MapTo(minMem, maxMem, 0 + graphOffset, graphHeight + graphOffset, line*1000*100) - 10, 100, 20), (line/10.0f).ToString("0.0 MB"));
GUI.color = Color.green;
// Round to nearest x.x MB
line = Mathf.Round(maxFPS);
GUI.Label(new Rect(55, Screen.height - AstarMath.MapTo(minFPS, maxFPS, 0 + graphOffset, graphHeight + graphOffset, line) - 10, 100, 20), line.ToString("0 FPS"));
line = Mathf.Round(minFPS);
GUI.Label(new Rect(55, Screen.height - AstarMath.MapTo(minFPS, maxFPS, 0 + graphOffset, graphHeight + graphOffset, line) - 10, 100, 20), line.ToString("0 FPS"));
}
}
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5103795af2d504ea693528e938005441
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}

View File

@@ -0,0 +1,100 @@
using UnityEngine;
namespace Pathfinding {
using Pathfinding.Util;
/// <summary>
/// Policy for how often to recalculate an agent's path.
///
/// See: \reflink{AIBase.autoRepath}
/// See: \reflink{AILerp.autoRepath}
/// </summary>
[System.Serializable]
public class AutoRepathPolicy {
/// <summary>Policy mode for how often to recalculate an agent's path.</summary>
public enum Mode {
/// <summary>
/// Never automatically recalculate the path.
/// Paths can be recalculated manually by for example calling \reflink{IAstarAI.SearchPath} or \reflink{IAstarAI.SetPath}.
/// This mode is useful if you want full control of when the agent calculates its path.
/// </summary>
Never,
/// <summary>Recalculate the path every \reflink{interval} seconds</summary>
EveryNSeconds,
/// <summary>
/// Recalculate the path at least every \reflink{maximumInterval} seconds but more often if the destination moves a lot.
/// This mode is recommended since it allows the agent to quickly respond to new destinations without using up a lot of CPU power to calculate paths
/// when it doesn't have to.
///
/// More precisely:\n
/// Let C be a circle centered at the destination for the last calculated path with a radius equal to the distance to that point divided by \reflink{sensitivity}.\n
/// If the new destination is outside that circle the path will be immediately recalculated.\n
/// Otherwise let F be the 1 - (distance from the circle's center to the new destination divided by the circle's radius).\n
/// So F will be 1 if the new destination is the same as the old one and 0 if it is at the circle's edge.\n
/// Recalculate the path if the time since the last path recalculation is greater than \reflink{maximumInterval} multiplied by F.\n
///
/// Thus if the destination doesn't change the path will be recalculated every \reflink{maximumInterval} seconds.
/// </summary>
Dynamic,
}
/// <summary>Policy to use when recalculating paths</summary>
public Mode mode = Mode.Dynamic;
/// <summary>Number of seconds between each automatic path recalculation for Mode.EveryNSeconds</summary>
public float interval = 0.5f;
/// <summary>
/// How sensitive the agent should be to changes in its destination for Mode.Dynamic.
/// A higher value means the destination has to move less for the path to be recalculated.
///
/// See: \reflink{Mode}
/// </summary>
public float sensitivity = 10.0f;
/// <summary>Maximum number of seconds between each automatic path recalculation for Mode.Dynamic</summary>
public float maximumInterval = 2.0f;
/// <summary>If true the sensitivity will be visualized as a circle in the scene view when the game is playing</summary>
public bool visualizeSensitivity = false;
Vector3 lastDestination = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
float lastRepathTime = float.NegativeInfinity;
/// <summary>True if the path should be recalculated according to the policy</summary>
public virtual bool ShouldRecalculatePath (IAstarAI ai) {
if (mode == Mode.Never || float.IsPositiveInfinity(ai.destination.x)) return false;
float timeSinceLast = Time.time - lastRepathTime;
if (mode == Mode.EveryNSeconds) {
return timeSinceLast >= interval;
} else {
// cost = change in destination / max(distance to destination, radius)
float squaredCost = (ai.destination - lastDestination).sqrMagnitude / Mathf.Max((ai.position - lastDestination).sqrMagnitude, ai.radius*ai.radius);
float fraction = squaredCost * (sensitivity*sensitivity);
if (fraction > 1.0f || float.IsNaN(fraction)) return true;
if (timeSinceLast >= maximumInterval*(1 - Mathf.Sqrt(fraction))) return true;
return false;
}
}
/// <summary>Reset the runtime variables so that the policy behaves as if the game just started</summary>
public virtual void Reset () {
lastRepathTime = float.NegativeInfinity;
}
/// <summary>Must be called when a path request has been scheduled</summary>
public virtual void DidRecalculatePath (Vector3 destination) {
lastRepathTime = Time.time;
lastDestination = destination;
}
public void DrawGizmos (IAstarAI ai) {
if (visualizeSensitivity && !float.IsPositiveInfinity(lastDestination.x)) {
float r = Mathf.Sqrt(Mathf.Max((ai.position - lastDestination).sqrMagnitude, ai.radius*ai.radius)/(sensitivity*sensitivity));
Draw.Gizmos.CircleXZ(lastDestination, r, Color.magenta);
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2664ef60fd2811ba280670298a6d312b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,324 @@
#pragma warning disable 162
#pragma warning disable 429
#define DECREASE_KEY
namespace Pathfinding {
/// <summary>
/// Binary heap implementation.
/// Binary heaps are really fast for ordering nodes in a way that
/// makes it possible to get the node with the lowest F score.
/// Also known as a priority queue.
///
/// This has actually been rewritten as a 4-ary heap
/// for performance, but it's the same principle.
///
/// See: http://en.wikipedia.org/wiki/Binary_heap
/// See: https://en.wikipedia.org/wiki/D-ary_heap
/// </summary>
public class BinaryHeap {
/// <summary>Number of items in the tree</summary>
public int numberOfItems;
/// <summary>The tree will grow by at least this factor every time it is expanded</summary>
public float growthFactor = 2;
/// <summary>
/// Number of children of each node in the tree.
/// Different values have been tested and 4 has been empirically found to perform the best.
/// See: https://en.wikipedia.org/wiki/D-ary_heap
/// </summary>
const int D = 4;
/// <summary>
/// Sort nodes by G score if there is a tie when comparing the F score.
/// Disabling this will improve pathfinding performance with around 2.5%
/// but may break ties between paths that have the same length in a less
/// desirable manner (only relevant for grid graphs).
/// </summary>
const bool SortGScores = true;
public const ushort NotInHeap = 0xFFFF;
/// <summary>Internal backing array for the heap</summary>
private Tuple[] heap;
/// <summary>True if the heap does not contain any elements</summary>
public bool isEmpty {
get {
return numberOfItems <= 0;
}
}
/// <summary>Item in the heap</summary>
private struct Tuple {
public PathNode node;
public uint F;
public Tuple (uint f, PathNode node) {
this.F = f;
this.node = node;
}
}
/// <summary>
/// Rounds up v so that it has remainder 1 when divided by D.
/// I.e it is of the form n*D + 1 where n is any non-negative integer.
/// </summary>
static int RoundUpToNextMultipleMod1 (int v) {
// I have a feeling there is a nicer way to do this
return v + (4 - ((v-1) % D)) % D;
}
/// <summary>Create a new heap with the specified initial capacity</summary>
public BinaryHeap (int capacity) {
// Make sure the size has remainder 1 when divided by D
// This allows us to always guarantee that indices used in the Remove method
// will never throw out of bounds exceptions
capacity = RoundUpToNextMultipleMod1(capacity);
heap = new Tuple[capacity];
numberOfItems = 0;
}
/// <summary>Removes all elements from the heap</summary>
public void Clear () {
#if DECREASE_KEY
// Clear all heap indices
// This is important to avoid bugs
for (int i = 0; i < numberOfItems; i++) {
heap[i].node.heapIndex = NotInHeap;
}
#endif
numberOfItems = 0;
}
internal PathNode GetNode (int i) {
return heap[i].node;
}
internal void SetF (int i, uint f) {
heap[i].F = f;
}
/// <summary>Expands to a larger backing array when the current one is too small</summary>
void Expand () {
// 65533 == 1 mod 4 and slightly smaller than 1<<16 = 65536
int newSize = System.Math.Max(heap.Length+4, System.Math.Min(65533, (int)System.Math.Round(heap.Length*growthFactor)));
// Make sure the size has remainder 1 when divided by D
// This allows us to always guarantee that indices used in the Remove method
// will never throw out of bounds exceptions
newSize = RoundUpToNextMultipleMod1(newSize);
// Check if the heap is really large
// Also note that heaps larger than this are not supported
// since PathNode.heapIndex is a ushort and can only store
// values up to 65535 (NotInHeap = 65535 is reserved however)
if (newSize > (1<<16) - 2) {
throw new System.Exception("Binary Heap Size really large (>65534). A heap size this large is probably the cause of pathfinding running in an infinite loop. ");
}
var newHeap = new Tuple[newSize];
heap.CopyTo(newHeap, 0);
#if ASTARDEBUG
UnityEngine.Debug.Log("Resizing binary heap to "+newSize);
#endif
heap = newHeap;
}
/// <summary>Adds a node to the heap</summary>
public void Add (PathNode node) {
if (node == null) throw new System.ArgumentNullException("node");
#if DECREASE_KEY
// Check if node is already in the heap
if (node.heapIndex != NotInHeap) {
DecreaseKey(heap[node.heapIndex], node.heapIndex);
return;
}
#endif
if (numberOfItems == heap.Length) {
Expand();
}
DecreaseKey(new Tuple(0, node), (ushort)numberOfItems);
numberOfItems++;
}
void DecreaseKey (Tuple node, ushort index) {
// This is where 'obj' is in the binary heap logically speaking
// (for performance reasons we don't actually store it there until
// we know the final index, that's just a waste of CPU cycles)
int bubbleIndex = index;
// Update F value, it might have changed since the node was originally added to the heap
uint nodeF = node.F = node.node.F;
uint nodeG = node.node.G;
while (bubbleIndex != 0) {
// Parent node of the bubble node
int parentIndex = (bubbleIndex-1) / D;
if (nodeF < heap[parentIndex].F || (SortGScores && nodeF == heap[parentIndex].F && nodeG > heap[parentIndex].node.G)) {
// Swap the bubble node and parent node
// (we don't really need to store the bubble node until we know the final index though
// so we do that after the loop instead)
heap[bubbleIndex] = heap[parentIndex];
#if DECREASE_KEY
heap[bubbleIndex].node.heapIndex = (ushort)bubbleIndex;
#endif
bubbleIndex = parentIndex;
} else {
break;
}
}
heap[bubbleIndex] = node;
#if DECREASE_KEY
node.node.heapIndex = (ushort)bubbleIndex;
#endif
}
/// <summary>Returns the node with the lowest F score from the heap</summary>
public PathNode Remove () {
PathNode returnItem = heap[0].node;
#if DECREASE_KEY
returnItem.heapIndex = NotInHeap;
#endif
numberOfItems--;
if (numberOfItems == 0) return returnItem;
// Last item in the heap array
var swapItem = heap[numberOfItems];
var swapItemG = swapItem.node.G;
int swapIndex = 0, parent;
// Trickle upwards
while (true) {
parent = swapIndex;
uint swapF = swapItem.F;
int pd = parent * D + 1;
// If this holds, then the indices used
// below are guaranteed to not throw an index out of bounds
// exception since we choose the size of the array in that way
if (pd <= numberOfItems) {
// Loading all F scores here instead of inside the if statements
// reduces data dependencies and improves performance
uint f0 = heap[pd+0].F;
uint f1 = heap[pd+1].F;
uint f2 = heap[pd+2].F;
uint f3 = heap[pd+3].F;
// The common case is that all children of a node are present
// so the first comparison in each if statement below
// will be extremely well predicted so it is essentially free
// (I tried optimizing for the common case, but it didn't affect performance at all
// at the expense of longer code, the CPU branch predictor is really good)
if (pd+0 < numberOfItems && (f0 < swapF || (SortGScores && f0 == swapF && heap[pd+0].node.G < swapItemG))) {
swapF = f0;
swapIndex = pd+0;
}
if (pd+1 < numberOfItems && (f1 < swapF || (SortGScores && f1 == swapF && heap[pd+1].node.G < (swapIndex == parent ? swapItemG : heap[swapIndex].node.G)))) {
swapF = f1;
swapIndex = pd+1;
}
if (pd+2 < numberOfItems && (f2 < swapF || (SortGScores && f2 == swapF && heap[pd+2].node.G < (swapIndex == parent ? swapItemG : heap[swapIndex].node.G)))) {
swapF = f2;
swapIndex = pd+2;
}
if (pd+3 < numberOfItems && (f3 < swapF || (SortGScores && f3 == swapF && heap[pd+3].node.G < (swapIndex == parent ? swapItemG : heap[swapIndex].node.G)))) {
swapIndex = pd+3;
}
}
// One if the parent's children are smaller or equal, swap them
// (actually we are just pretenting we swapped them, we hold the swapData
// in local variable and only assign it once we know the final index)
if (parent != swapIndex) {
heap[parent] = heap[swapIndex];
#if DECREASE_KEY
heap[parent].node.heapIndex = (ushort)parent;
#endif
} else {
break;
}
}
// Assign element to the final position
heap[swapIndex] = swapItem;
#if DECREASE_KEY
swapItem.node.heapIndex = (ushort)swapIndex;
#endif
// For debugging
// Validate ();
return returnItem;
}
void Validate () {
for (int i = 1; i < numberOfItems; i++) {
int parentIndex = (i-1)/D;
if (heap[parentIndex].F > heap[i].F) {
throw new System.Exception("Invalid state at " + i + ":" + parentIndex + " ( " + heap[parentIndex].F + " > " + heap[i].F + " ) ");
}
#if DECREASE_KEY
if (heap[i].node.heapIndex != i) {
throw new System.Exception("Invalid heap index");
}
#endif
}
}
/// <summary>
/// Rebuilds the heap by trickeling down all items.
/// Usually called after the hTarget on a path has been changed
/// </summary>
public void Rebuild () {
#if ASTARDEBUG
int changes = 0;
#endif
for (int i = 2; i < numberOfItems; i++) {
int bubbleIndex = i;
var node = heap[i];
uint nodeF = node.F;
while (bubbleIndex != 1) {
int parentIndex = bubbleIndex / D;
if (nodeF < heap[parentIndex].F) {
heap[bubbleIndex] = heap[parentIndex];
#if DECREASE_KEY
heap[bubbleIndex].node.heapIndex = (ushort)bubbleIndex;
#endif
heap[parentIndex] = node;
#if DECREASE_KEY
heap[parentIndex].node.heapIndex = (ushort)parentIndex;
#endif
bubbleIndex = parentIndex;
#if ASTARDEBUG
changes++;
#endif
} else {
break;
}
}
}
#if ASTARDEBUG
UnityEngine.Debug.Log("+++ Rebuilt Heap - "+changes+" changes +++");
#endif
}
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: eb4299e8747f44ad2b4e086752108ea3
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}

View File

@@ -0,0 +1,91 @@
using UnityEngine;
namespace Pathfinding.Util {
/// <summary>Helper methods for drawing gizmos and debug lines</summary>
public class Draw {
public static readonly Draw Debug = new Draw { gizmos = false };
public static readonly Draw Gizmos = new Draw { gizmos = true };
bool gizmos;
Matrix4x4 matrix = Matrix4x4.identity;
void SetColor (Color color) {
if (gizmos && UnityEngine.Gizmos.color != color) UnityEngine.Gizmos.color = color;
}
public void Polyline (System.Collections.Generic.List<Vector3> points, Color color, bool cycle = false) {
for (int i = 0; i < points.Count - 1; i++) {
Line(points[i], points[i+1], color);
}
if (cycle && points.Count > 1) Line(points[points.Count - 1], points[0], color);
}
public void Line (Vector3 a, Vector3 b, Color color) {
SetColor(color);
if (gizmos) UnityEngine.Gizmos.DrawLine(matrix.MultiplyPoint3x4(a), matrix.MultiplyPoint3x4(b));
else UnityEngine.Debug.DrawLine(matrix.MultiplyPoint3x4(a), matrix.MultiplyPoint3x4(b), color);
}
public void CircleXZ (Vector3 center, float radius, Color color, float startAngle = 0f, float endAngle = 2*Mathf.PI) {
int steps = 40;
#if UNITY_EDITOR
if (gizmos) steps = (int)Mathf.Clamp(Mathf.Sqrt(radius / UnityEditor.HandleUtility.GetHandleSize((UnityEngine.Gizmos.matrix * matrix).MultiplyPoint3x4(center))) * 25, 4, 40);
#endif
while (startAngle > endAngle) startAngle -= 2*Mathf.PI;
Vector3 prev = new Vector3(Mathf.Cos(startAngle)*radius, 0, Mathf.Sin(startAngle)*radius);
for (int i = 0; i <= steps; i++) {
Vector3 c = new Vector3(Mathf.Cos(Mathf.Lerp(startAngle, endAngle, i/(float)steps))*radius, 0, Mathf.Sin(Mathf.Lerp(startAngle, endAngle, i/(float)steps))*radius);
Line(center + prev, center + c, color);
prev = c;
}
}
public void Cylinder (Vector3 position, Vector3 up, float height, float radius, Color color) {
var tangent = Vector3.Cross(up, Vector3.one).normalized;
matrix = Matrix4x4.TRS(position, Quaternion.LookRotation(tangent, up), new Vector3(radius, height, radius));
CircleXZ(Vector3.zero, 1, color);
if (height > 0) {
CircleXZ(Vector3.up, 1, color);
Line(new Vector3(1, 0, 0), new Vector3(1, 1, 0), color);
Line(new Vector3(-1, 0, 0), new Vector3(-1, 1, 0), color);
Line(new Vector3(0, 0, 1), new Vector3(0, 1, 1), color);
Line(new Vector3(0, 0, -1), new Vector3(0, 1, -1), color);
}
matrix = Matrix4x4.identity;
}
public void CrossXZ (Vector3 position, Color color, float size = 1) {
size *= 0.5f;
Line(position - Vector3.right*size, position + Vector3.right*size, color);
Line(position - Vector3.forward*size, position + Vector3.forward*size, color);
}
public void Bezier (Vector3 a, Vector3 b, Color color) {
Vector3 dir = b - a;
if (dir == Vector3.zero) return;
Vector3 normal = Vector3.Cross(Vector3.up, dir);
Vector3 normalUp = Vector3.Cross(dir, normal);
normalUp = normalUp.normalized;
normalUp *= dir.magnitude*0.1f;
Vector3 p1c = a + normalUp;
Vector3 p2c = b + normalUp;
Vector3 prev = a;
for (int i = 1; i <= 20; i++) {
float t = i/20.0f;
Vector3 p = AstarSplines.CubicBezier(a, p1c, p2c, b, t);
Line(prev, p, color);
prev = p;
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 506739df886ce4ebb9b14b16d86b5e13
timeCreated: 1492346087
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,105 @@
namespace Pathfinding {
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
/// <summary>Internal utility class for looking up editor resources</summary>
public static class EditorResourceHelper {
/// <summary>
/// Path to the editor assets folder for the A* Pathfinding Project. If this path turns out to be incorrect, the script will try to find the correct path
/// See: LoadStyles
/// </summary>
public static string editorAssets;
static EditorResourceHelper () {
// Look up editor assets directory when first accessed
LocateEditorAssets();
}
static Material surfaceMat, lineMat;
static Texture2D handlesAALineTex;
public static Material GizmoSurfaceMaterial {
get {
if (!surfaceMat) surfaceMat = UnityEditor.AssetDatabase.LoadAssetAtPath(EditorResourceHelper.editorAssets + "/Materials/Navmesh.mat", typeof(Material)) as Material;
return surfaceMat;
}
}
public static Material GizmoLineMaterial {
get {
if (!lineMat) lineMat = UnityEditor.AssetDatabase.LoadAssetAtPath(EditorResourceHelper.editorAssets + "/Materials/NavmeshOutline.mat", typeof(Material)) as Material;
return lineMat;
}
}
public static Texture2D HandlesAALineTexture {
get {
if (!handlesAALineTex) handlesAALineTex = Resources.Load<Texture2D>("handles_aaline");
return handlesAALineTex;
}
}
/// <summary>Locates the editor assets folder in case the user has moved it</summary>
public static bool LocateEditorAssets () {
#if UNITY_2019_3_OR_NEWER
var package = UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(EditorResourceHelper).Assembly);
if (package != null) {
editorAssets = package.assetPath + "/Editor/EditorAssets";
if (System.IO.File.Exists(package.resolvedPath + "/Editor/EditorAssets/AstarEditorSkinLight.guiskin")) {
return true;
} else {
Debug.LogError("Could not find editor assets folder in package at " + editorAssets + ". Is the package corrupt?");
return false;
}
}
#endif
string projectPath = Application.dataPath;
if (projectPath.EndsWith("/Assets")) {
projectPath = projectPath.Remove(projectPath.Length-("Assets".Length));
}
editorAssets = "Assets/AstarPathfindingProject/Editor/EditorAssets";
if (!System.IO.File.Exists(projectPath + editorAssets + "/AstarEditorSkinLight.guiskin") && !System.IO.File.Exists(projectPath + editorAssets + "/AstarEditorSkin.guiskin")) {
//Initiate search
var sdir = new System.IO.DirectoryInfo(Application.dataPath);
var dirQueue = new Queue<System.IO.DirectoryInfo>();
dirQueue.Enqueue(sdir);
bool found = false;
while (dirQueue.Count > 0) {
System.IO.DirectoryInfo dir = dirQueue.Dequeue();
if (System.IO.File.Exists(dir.FullName + "/AstarEditorSkinLight.guiskin") || System.IO.File.Exists(dir.FullName + "/AstarEditorSkin.guiskin")) {
// Handle windows file paths
string path = dir.FullName.Replace('\\', '/');
found = true;
// Remove data path from string to make it relative
path = path.Replace(projectPath, "");
if (path.StartsWith("/")) {
path = path.Remove(0, 1);
}
editorAssets = path;
return true;
}
var dirs = dir.GetDirectories();
for (int i = 0; i < dirs.Length; i++) {
dirQueue.Enqueue(dirs[i]);
}
}
if (!found) {
Debug.LogWarning("Could not locate editor assets folder. Make sure you have imported the package correctly.\nA* Pathfinding Project");
return false;
}
}
return true;
}
}
#endif
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 8127bc49e9e2d42dfa7a4e057842f165
timeCreated: 1480419306
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,10 @@
using Pathfinding.Serialization;
namespace Pathfinding {
[JsonOptIn]
/// <summary>Defined here only so non-editor classes can use the <see cref="target"/> field</summary>
public class GraphEditorBase {
/// <summary>NavGraph this editor is exposing</summary>
public NavGraph target;
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 704136724bc95455ebe477f42f5c5a84
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}

View File

@@ -0,0 +1,204 @@
using UnityEngine;
using System.Collections.Generic;
namespace Pathfinding {
/// <summary>
/// GraphModifier is used for modifying graphs or processing graph data based on events.
/// This class is a simple container for a number of events.
///
/// Warning: Some events will be called both in play mode <b>and in editor mode</b> (at least the scan events).
/// So make sure your code handles both cases well. You may choose to ignore editor events.
/// See: Application.IsPlaying
/// </summary>
[ExecuteInEditMode]
public abstract class GraphModifier : VersionedMonoBehaviour {
/// <summary>All active graph modifiers</summary>
private static GraphModifier root;
private GraphModifier prev;
private GraphModifier next;
/// <summary>Unique persistent ID for this component, used for serialization</summary>
[SerializeField]
[HideInInspector]
protected ulong uniqueID;
/// <summary>Maps persistent IDs to the component that uses it</summary>
protected static Dictionary<ulong, GraphModifier> usedIDs = new Dictionary<ulong, GraphModifier>();
protected static List<T> GetModifiersOfType<T>() where T : GraphModifier {
var current = root;
var result = new List<T>();
while (current != null) {
var cast = current as T;
if (cast != null) result.Add(cast);
current = current.next;
}
return result;
}
public static void FindAllModifiers () {
var allModifiers = FindObjectsOfType(typeof(GraphModifier)) as GraphModifier[];
for (int i = 0; i < allModifiers.Length; i++) {
if (allModifiers[i].enabled) allModifiers[i].OnEnable();
}
}
/// <summary>GraphModifier event type</summary>
public enum EventType {
PostScan = 1 << 0,
PreScan = 1 << 1,
LatePostScan = 1 << 2,
PreUpdate = 1 << 3,
PostUpdate = 1 << 4,
PostCacheLoad = 1 << 5
}
/// <summary>Triggers an event for all active graph modifiers</summary>
public static void TriggerEvent (GraphModifier.EventType type) {
if (!Application.isPlaying) {
FindAllModifiers();
}
GraphModifier c = root;
switch (type) {
case EventType.PreScan:
while (c != null) { c.OnPreScan(); c = c.next; }
break;
case EventType.PostScan:
while (c != null) { c.OnPostScan(); c = c.next; }
break;
case EventType.LatePostScan:
while (c != null) { c.OnLatePostScan(); c = c.next; }
break;
case EventType.PreUpdate:
while (c != null) { c.OnGraphsPreUpdate(); c = c.next; }
break;
case EventType.PostUpdate:
while (c != null) { c.OnGraphsPostUpdate(); c = c.next; }
break;
case EventType.PostCacheLoad:
while (c != null) { c.OnPostCacheLoad(); c = c.next; }
break;
}
}
/// <summary>Adds this modifier to list of active modifiers</summary>
protected virtual void OnEnable () {
RemoveFromLinkedList();
AddToLinkedList();
ConfigureUniqueID();
}
/// <summary>Removes this modifier from list of active modifiers</summary>
protected virtual void OnDisable () {
RemoveFromLinkedList();
}
protected override void Awake () {
base.Awake();
ConfigureUniqueID();
}
void ConfigureUniqueID () {
// Check if any other object is using the same uniqueID
// In that case this object may have been duplicated
GraphModifier usedBy;
if (usedIDs.TryGetValue(uniqueID, out usedBy) && usedBy != this) {
Reset();
}
usedIDs[uniqueID] = this;
}
void AddToLinkedList () {
if (root == null) {
root = this;
} else {
next = root;
root.prev = this;
root = this;
}
}
void RemoveFromLinkedList () {
if (root == this) {
root = next;
if (root != null) root.prev = null;
} else {
if (prev != null) prev.next = next;
if (next != null) next.prev = prev;
}
prev = null;
next = null;
}
protected virtual void OnDestroy () {
usedIDs.Remove(uniqueID);
}
/// <summary>
/// Called right after all graphs have been scanned.
/// FloodFill and other post processing has not been done.
///
/// Warning: Since OnEnable and Awake are called roughly in the same time, the only way
/// to ensure that these scripts get this call when scanning in Awake is to
/// set the Script Execution Order for AstarPath to some time later than default time
/// (see Edit -> Project Settings -> Script Execution Order).
/// TODO: Is this still relevant? A call to FindAllModifiers should have before this method is called
/// so the above warning is probably not relevant anymore.
///
/// See: OnLatePostScan
/// </summary>
public virtual void OnPostScan () {}
/// <summary>
/// Called right before graphs are going to be scanned.
///
/// Warning: Since OnEnable and Awake are called roughly in the same time, the only way
/// to ensure that these scripts get this call when scanning in Awake is to
/// set the Script Execution Order for AstarPath to some time later than default time
/// (see Edit -> Project Settings -> Script Execution Order).
/// TODO: Is this still relevant? A call to FindAllModifiers should have before this method is called
/// so the above warning is probably not relevant anymore.
///
/// See: OnLatePostScan
/// </summary>
public virtual void OnPreScan () {}
/// <summary>
/// Called at the end of the scanning procedure.
/// This is the absolute last thing done by Scan.
/// </summary>
public virtual void OnLatePostScan () {}
/// <summary>
/// Called after cached graphs have been loaded.
/// When using cached startup, this event is analogous to OnLatePostScan and implementing scripts
/// should do roughly the same thing for both events.
/// </summary>
public virtual void OnPostCacheLoad () {}
/// <summary>Called before graphs are updated using GraphUpdateObjects</summary>
public virtual void OnGraphsPreUpdate () {}
/// <summary>
/// Called after graphs have been updated using GraphUpdateObjects.
/// Eventual flood filling has been done
/// </summary>
public virtual void OnGraphsPostUpdate () {}
protected override void Reset () {
base.Reset();
// Create a new random 64 bit value (62 bit actually because we skip negative numbers, but that's still enough by a huge margin)
var rnd1 = (ulong)Random.Range(0, int.MaxValue);
var rnd2 = ((ulong)Random.Range(0, int.MaxValue) << 32);
uniqueID = rnd1 | rnd2;
usedIDs[uniqueID] = this;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 39897fb482672480a817862c3909a4aa
timeCreated: 1490044676
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: -222
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,369 @@
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
#if UNITY_5_5_OR_NEWER
using UnityEngine.Profiling;
#endif
namespace Pathfinding {
using UnityEngine.Assertions;
#if NETFX_CORE
using Thread = Pathfinding.WindowsStore.Thread;
#else
using Thread = System.Threading.Thread;
#endif
class GraphUpdateProcessor {
public event System.Action OnGraphsUpdated;
/// <summary>Holds graphs that can be updated</summary>
readonly AstarPath astar;
#if !UNITY_WEBGL
/// <summary>
/// Reference to the thread which handles async graph updates.
/// See: ProcessGraphUpdatesAsync
/// </summary>
Thread graphUpdateThread;
#endif
/// <summary>Used for IsAnyGraphUpdateInProgress</summary>
bool anyGraphUpdateInProgress;
#if UNITY_2017_3_OR_NEWER && !UNITY_WEBGL
CustomSampler asyncUpdateProfilingSampler;
#endif
/// <summary>
/// Queue containing all waiting graph update queries. Add to this queue by using \link AddToQueue \endlink.
/// See: AddToQueue
/// </summary>
readonly Queue<GraphUpdateObject> graphUpdateQueue = new Queue<GraphUpdateObject>();
/// <summary>Queue of all async graph updates waiting to be executed</summary>
readonly Queue<GUOSingle> graphUpdateQueueAsync = new Queue<GUOSingle>();
/// <summary>Queue of all non-async graph update post events waiting to be executed</summary>
readonly Queue<GUOSingle> graphUpdateQueuePost = new Queue<GUOSingle>();
/// <summary>Queue of all non-async graph updates waiting to be executed</summary>
readonly Queue<GUOSingle> graphUpdateQueueRegular = new Queue<GUOSingle>();
readonly System.Threading.ManualResetEvent asyncGraphUpdatesComplete = new System.Threading.ManualResetEvent(true);
#if !UNITY_WEBGL
readonly System.Threading.AutoResetEvent graphUpdateAsyncEvent = new System.Threading.AutoResetEvent(false);
readonly System.Threading.AutoResetEvent exitAsyncThread = new System.Threading.AutoResetEvent(false);
#endif
/// <summary>Returns if any graph updates are waiting to be applied</summary>
public bool IsAnyGraphUpdateQueued { get { return graphUpdateQueue.Count > 0; } }
/// <summary>Returns if any graph updates are in progress</summary>
public bool IsAnyGraphUpdateInProgress { get { return anyGraphUpdateInProgress; } }
/// <summary>Order type for updating graphs</summary>
enum GraphUpdateOrder {
GraphUpdate,
// FloodFill
}
/// <summary>Holds a single update that needs to be performed on a graph</summary>
struct GUOSingle {
public GraphUpdateOrder order;
public IUpdatableGraph graph;
public GraphUpdateObject obj;
}
public GraphUpdateProcessor (AstarPath astar) {
this.astar = astar;
}
/// <summary>Work item which can be used to apply all queued updates</summary>
public AstarWorkItem GetWorkItem () {
return new AstarWorkItem(QueueGraphUpdatesInternal, ProcessGraphUpdates);
}
public void EnableMultithreading () {
#if !UNITY_WEBGL
if (graphUpdateThread == null || !graphUpdateThread.IsAlive) {
#if UNITY_2017_3_OR_NEWER && !UNITY_WEBGL
asyncUpdateProfilingSampler = CustomSampler.Create("Graph Update");
#endif
graphUpdateThread = new Thread(ProcessGraphUpdatesAsync);
graphUpdateThread.IsBackground = true;
// Set the thread priority for graph updates
// Unless compiling for windows store or windows phone which does not support it
#if !UNITY_WINRT
graphUpdateThread.Priority = System.Threading.ThreadPriority.Lowest;
#endif
graphUpdateThread.Start();
}
#endif
}
public void DisableMultithreading () {
#if !UNITY_WEBGL
if (graphUpdateThread != null && graphUpdateThread.IsAlive) {
// Resume graph update thread, will cause it to terminate
exitAsyncThread.Set();
if (!graphUpdateThread.Join(5*1000)) {
Debug.LogError("Graph update thread did not exit in 5 seconds");
}
graphUpdateThread = null;
}
#endif
}
/// <summary>
/// Update all graphs using the GraphUpdateObject.
/// This can be used to, e.g make all nodes in an area unwalkable, or set them to a higher penalty.
/// The graphs will be updated as soon as possible (with respect to AstarPath.batchGraphUpdates)
///
/// See: FlushGraphUpdates
/// </summary>
public void AddToQueue (GraphUpdateObject ob) {
// Put the GUO in the queue
graphUpdateQueue.Enqueue(ob);
}
/// <summary>Schedules graph updates internally</summary>
void QueueGraphUpdatesInternal () {
while (graphUpdateQueue.Count > 0) {
GraphUpdateObject ob = graphUpdateQueue.Dequeue();
if (ob.internalStage != GraphUpdateObject.STAGE_PENDING) {
Debug.LogError("Expected remaining graph updates to be pending");
continue;
}
ob.internalStage = 0;
foreach (IUpdatableGraph g in astar.data.GetUpdateableGraphs()) {
NavGraph gr = g as NavGraph;
if (ob.nnConstraint == null || ob.nnConstraint.SuitableGraph(astar.data.GetGraphIndex(gr), gr)) {
var guo = new GUOSingle();
guo.order = GraphUpdateOrder.GraphUpdate;
guo.obj = ob;
guo.graph = g;
ob.internalStage += 1;
graphUpdateQueueRegular.Enqueue(guo);
}
}
}
GraphModifier.TriggerEvent(GraphModifier.EventType.PreUpdate);
anyGraphUpdateInProgress = true;
}
/// <summary>
/// Updates graphs.
/// Will do some graph updates, possibly signal another thread to do them.
/// Will only process graph updates added by QueueGraphUpdatesInternal
///
/// Returns: True if all graph updates have been done and pathfinding (or other tasks) may resume.
/// False if there are still graph updates being processed or waiting in the queue.
/// </summary>
/// <param name="force">If true, all graph updates will be processed before this function returns. The return value
/// will be True.</param>
bool ProcessGraphUpdates (bool force) {
Assert.IsTrue(anyGraphUpdateInProgress);
if (force) {
asyncGraphUpdatesComplete.WaitOne();
} else {
#if !UNITY_WEBGL
if (!asyncGraphUpdatesComplete.WaitOne(0)) {
return false;
}
#endif
}
Assert.AreEqual(graphUpdateQueueAsync.Count, 0, "Queue should be empty at this stage");
ProcessPostUpdates();
if (!ProcessRegularUpdates(force)) {
return false;
}
GraphModifier.TriggerEvent(GraphModifier.EventType.PostUpdate);
if (OnGraphsUpdated != null) OnGraphsUpdated();
Assert.AreEqual(graphUpdateQueueRegular.Count, 0, "QueueRegular should be empty at this stage");
Assert.AreEqual(graphUpdateQueueAsync.Count, 0, "QueueAsync should be empty at this stage");
Assert.AreEqual(graphUpdateQueuePost.Count, 0, "QueuePost should be empty at this stage");
anyGraphUpdateInProgress = false;
return true;
}
bool ProcessRegularUpdates (bool force) {
while (graphUpdateQueueRegular.Count > 0) {
GUOSingle s = graphUpdateQueueRegular.Peek();
GraphUpdateThreading threading = s.graph.CanUpdateAsync(s.obj);
#if UNITY_WEBGL
// Never use multithreading in WebGL
threading &= ~GraphUpdateThreading.SeparateThread;
#else
// When not playing or when not using a graph update thread (or if it has crashed), everything runs in the Unity thread
if (force || !Application.isPlaying || graphUpdateThread == null || !graphUpdateThread.IsAlive) {
// Remove the SeparateThread flag
threading &= ~GraphUpdateThreading.SeparateThread;
}
#endif
if ((threading & GraphUpdateThreading.UnityInit) != 0) {
// Process async graph updates first.
// Next call to this function will process this object so it is not dequeued now
if (StartAsyncUpdatesIfQueued()) {
return false;
}
s.graph.UpdateAreaInit(s.obj);
}
if ((threading & GraphUpdateThreading.SeparateThread) != 0) {
// Move GUO to async queue to be updated by another thread
graphUpdateQueueRegular.Dequeue();
graphUpdateQueueAsync.Enqueue(s);
// Don't start any more async graph updates because this update
// requires a Unity thread function to run after it has been completed
// but before the next update is started
if ((threading & GraphUpdateThreading.UnityPost) != 0) {
if (StartAsyncUpdatesIfQueued()) {
return false;
}
}
} else {
// Unity Thread
if (StartAsyncUpdatesIfQueued()) {
return false;
}
graphUpdateQueueRegular.Dequeue();
try {
s.graph.UpdateArea(s.obj);
} catch (System.Exception e) {
Debug.LogError("Error while updating graphs\n"+e);
}
if ((threading & GraphUpdateThreading.UnityPost) != 0) {
s.graph.UpdateAreaPost(s.obj);
}
s.obj.internalStage -= 1;
UnityEngine.Assertions.Assert.IsTrue(s.obj.internalStage >= 0);
}
}
if (StartAsyncUpdatesIfQueued()) {
return false;
}
return true;
}
/// <summary>
/// Signal the graph update thread to start processing graph updates if there are any in the <see cref="graphUpdateQueueAsync"/> queue.
/// Returns: True if the other thread was signaled.
/// </summary>
bool StartAsyncUpdatesIfQueued () {
if (graphUpdateQueueAsync.Count > 0) {
#if UNITY_WEBGL
throw new System.Exception("This should not happen in WebGL");
#else
asyncGraphUpdatesComplete.Reset();
graphUpdateAsyncEvent.Set();
return true;
#endif
}
return false;
}
void ProcessPostUpdates () {
while (graphUpdateQueuePost.Count > 0) {
GUOSingle s = graphUpdateQueuePost.Dequeue();
GraphUpdateThreading threading = s.graph.CanUpdateAsync(s.obj);
if ((threading & GraphUpdateThreading.UnityPost) != 0) {
try {
s.graph.UpdateAreaPost(s.obj);
} catch (System.Exception e) {
Debug.LogError("Error while updating graphs (post step)\n"+e);
}
}
s.obj.internalStage -= 1;
UnityEngine.Assertions.Assert.IsTrue(s.obj.internalStage >= 0);
}
}
#if !UNITY_WEBGL
/// <summary>
/// Graph update thread.
/// Async graph updates will be executed by this method in another thread.
/// </summary>
void ProcessGraphUpdatesAsync () {
#if UNITY_2017_3_OR_NEWER
Profiler.BeginThreadProfiling("Pathfinding", "Threaded Graph Updates");
#endif
var handles = new [] { graphUpdateAsyncEvent, exitAsyncThread };
while (true) {
// Wait for the next batch or exit event
var handleIndex = WaitHandle.WaitAny(handles);
if (handleIndex == 1) {
// Exit even was fired
// Abort thread and clear queue
while (graphUpdateQueueAsync.Count > 0) {
var s = graphUpdateQueueAsync.Dequeue();
s.obj.internalStage = GraphUpdateObject.STAGE_ABORTED;
}
asyncGraphUpdatesComplete.Set();
#if UNITY_2017_3_OR_NEWER
Profiler.EndThreadProfiling();
#endif
return;
}
while (graphUpdateQueueAsync.Count > 0) {
#if UNITY_2017_3_OR_NEWER
asyncUpdateProfilingSampler.Begin();
#endif
// Note that no locking is required here because the main thread
// cannot access it until asyncGraphUpdatesComplete is signaled
GUOSingle aguo = graphUpdateQueueAsync.Dequeue();
try {
if (aguo.order == GraphUpdateOrder.GraphUpdate) {
aguo.graph.UpdateArea(aguo.obj);
graphUpdateQueuePost.Enqueue(aguo);
} else {
throw new System.NotSupportedException("" + aguo.order);
}
} catch (System.Exception e) {
Debug.LogError("Exception while updating graphs:\n"+e);
}
#if UNITY_2017_3_OR_NEWER
asyncUpdateProfilingSampler.End();
#endif
}
// Done
asyncGraphUpdatesComplete.Set();
}
}
#endif
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b1798d8e7c7d54972ae8522558cbd27c
timeCreated: 1443114816
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

Some files were not shown because too many files have changed in this diff Show More