浏览代码

Merge branch 'merge-branch' into demo-work

/demo-work-customrenderer
Mike Geig 5 年前
当前提交
5611be45
共有 51 个文件被更改,包括 3903 次插入425 次删除
  1. 748
      Assets/Objects/boats/Prefabs/_Boat.prefab
  2. 6
      Assets/Scripts/Boat/AIcontroller.cs
  3. 17
      Assets/Scripts/Boat/BoatController.cs
  4. 26
      Assets/Scripts/Boat/Engine.cs
  5. 4
      Assets/Scripts/Boat/HumanController.cs
  6. 10
      Assets/Scripts/GameSystem/RaceManager.cs
  7. 3
      Assets/Scripts/GameSystem/WaypointGroup.cs
  8. 54
      Assets/scenes/Island.unity
  9. 17
      Packages/com.verasl.water-system/Scripts/BuoyantObject.cs
  10. 43
      Packages/com.verasl.water-system/Scripts/Water.cs
  11. 3
      Packages/manifest.json
  12. 32
      ProjectSettings/ProjectSettings.asset
  13. 8
      Assets/EntityCache.meta
  14. 8
      Assets/Unity Physics Items.meta
  15. 8
      Assets/EntityCache/Resources.meta
  16. 7
      Assets/Unity Physics Items/Physics Scene.unity.meta
  17. 8
      Assets/Unity Physics Items/Components.meta
  18. 8
      Assets/Unity Physics Items/Prefabs.meta
  19. 8
      Assets/Unity Physics Items/Systems.meta
  20. 11
      Assets/Unity Physics Items/BuoyantObject_DOTS.cs.meta
  21. 11
      Assets/Unity Physics Items/AIController_DOTS.cs.meta
  22. 15
      Assets/Unity Physics Items/BoatBodyComponent.cs
  23. 375
      Assets/Unity Physics Items/BuoyantObject_DOTS.cs
  24. 11
      Assets/Unity Physics Items/Components/BoatDataComponents.cs.meta
  25. 33
      Assets/Unity Physics Items/Components/BoatDataComponents.cs
  26. 11
      Assets/Unity Physics Items/Systems/ApplyBuoyancyForceSystem.cs.meta
  27. 11
      Assets/Unity Physics Items/Systems/DriveSystem.cs.meta
  28. 11
      Assets/Unity Physics Items/Systems/GertsnerSystem.cs.meta
  29. 11
      Assets/Unity Physics Items/Systems/PhysicsConversionSystem.cs.meta
  30. 127
      Assets/Unity Physics Items/Systems/GertsnerSystem.cs
  31. 21
      Assets/Unity Physics Items/Systems/PhysicsConversionSystem.cs
  32. 96
      Assets/Unity Physics Items/Systems/ApplyBuoyancyForceSystem.cs
  33. 68
      Assets/Unity Physics Items/Systems/DriveSystem.cs
  34. 54
      Assets/Unity Physics Items/Systems/InputSystem.cs
  35. 11
      Assets/Unity Physics Items/Systems/InputSystem.cs.meta
  36. 11
      Assets/Unity Physics Items/BoatBodyComponent.cs.meta
  37. 115
      Assets/Unity Physics Items/AIController_DOTS.cs
  38. 1001
      Assets/Unity Physics Items/Physics Scene.unity
  39. 7
      Assets/Unity Physics Items/Prefabs/BoatEntity.prefab.meta
  40. 88
      Assets/Unity Physics Items/Prefabs/Physics Settings.prefab
  41. 7
      Assets/Unity Physics Items/Prefabs/Physics Settings.prefab.meta
  42. 8
      Assets/Unity Physics Items/Prefabs/Slippery.asset.meta
  43. 42
      Assets/Unity Physics Items/Prefabs/Slippery.asset
  44. 7
      Assets/Unity Physics Items/Prefabs/AIBoatEntity Variant.prefab.meta
  45. 1001
      Assets/Unity Physics Items/Prefabs/BoatEntity.prefab
  46. 146
      Assets/Unity Physics Items/Prefabs/AIBoatEntity Variant.prefab

748
Assets/Objects/boats/Prefabs/_Boat.prefab
文件差异内容过多而无法显示
查看文件

6
Assets/Scripts/Boat/AIcontroller.cs


// Use this for initialization
void Start ()
{
float delay = WaypointGroup.instance.raceDelay;
Invoke("GetNearestWP", delay);
float delay = WaypointGroup.raceDelay;
engine = GetComponent<Engine>(); // get the engine script
Invoke("GetNearestWP", delay);
}
// Update is called once per frame

17
Assets/Scripts/Boat/BoatController.cs


public Color PrimaryColor; // Boat primary colour
public Color TrimColor; // Boat secondary colour
public Renderer boatRenderer; // The renderer for the boat mesh
public Engine engine;
public CinemachineVirtualCamera cam;
void OnValidate()

// Use this for initialization
void Start()
void Awake()
{
Colourize();
}
// Use this for initialization
void Start()
Colourize();
gameObject.AddComponent<HumanController>().engine = engine; // Adds a human controller if human
gameObject.AddComponent<HumanController>(); // Adds a human controller if human
gameObject.AddComponent<AIcontroller>().engine = engine; // Adds an AI controller if AI
gameObject.AddComponent<AIcontroller>(); // Adds an AI controller if AI
}
}

26
Assets/Scripts/Boat/Engine.cs


using System.Collections;
using WaterSystem;
using Unity.Mathematics;
using Unity.Entities;
namespace BoatAttack.Boat
{

void Awake()
{
engineSound.time = UnityEngine.Random.Range(0f, engineSound.clip.length); // randomly start the engine sound
RB = gameObject.GetComponent<Rigidbody>();
engineSound.time = UnityEngine.Random.Range(0f, engineSound.clip.length); // randomly start the engine sound
waterSound.time = UnityEngine.Random.Range(0f, waterSound.clip.length); // randomly start the water sound
_guid = this.GetInstanceID(); // Get the engines GUID for the buoyancy system

Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawCube(enginePosition, new Vector3(0.1f, 0.2f, 0.3f)); // Draw teh engine position with sphere
}
}
//Called by parent BuoyantObject_DOTS
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
//Set up driving data
bool isHuman = GetComponent<BoatController>().Human;
if (!isHuman)
AIController_DOTS.Register(entity);
var data = new DrivingData
{
isHuman = isHuman,
torque = torque,
horsePower = horsePower,
engineOffset = transform.TransformPoint(enginePosition) - transform.position
};
dstManager.AddComponentData(entity, data);
}
}
}

4
Assets/Scripts/Boat/HumanController.cs


controls.BoatControls.Steering.performed += context => steering = context.ReadValue<float>();
controls.BoatControls.Steering.canceled += context => steering = 0f;
}
engine = GetComponent<Engine>(); // get the engine script
}
private void OnEnable()
{

10
Assets/Scripts/GameSystem/RaceManager.cs


public bool reversed;
}
public Race raceData;
public bool useDOTS;
public GameObject humanBoat;
public GameObject aiBoat;
public Race raceData;
private void Start()
{

{
var matrix = WaypointGroup.instance.startingPositons[i];
GameObject boatObject = Instantiate(boat.boatPrefab, matrix.GetColumn(3), Quaternion.LookRotation(matrix.GetColumn(2))) as GameObject;
var prefab = useDOTS ? (boat.Human ? humanBoat : aiBoat) : boat.boatPrefab;
GameObject boatObject = Instantiate(prefab, matrix.GetColumn(3), Quaternion.LookRotation(matrix.GetColumn(2))) as GameObject;
boatObject.name = boat.boatName;
BoatController boatController = boatObject.GetComponent<BoatController>();
boatController.Human = boat.Human;

3
Assets/Scripts/GameSystem/WaypointGroup.cs


public class WaypointGroup : MonoBehaviour
{
static WaypointGroup Instance = null;
public static float raceDelay = 4f;
public float raceDelay = 4f;
public bool raceStarted = false;
[NonSerialized]

54
Assets/scenes/Island.unity


m_OnCameraLive:
m_PersistentCalls:
m_Calls: []
m_TypeName: Cinemachine.CinemachineBrain+VcamActivatedEvent, Cinemachine, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
m_LegacyBlendHint: 0
m_ComponentOwner: {fileID: 602916014}
--- !u!95 &56310422

m_OnCameraLive:
m_PersistentCalls:
m_Calls: []
m_TypeName: Cinemachine.CinemachineBrain+VcamActivatedEvent, Cinemachine, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
m_LegacyBlendHint: 0
m_ComponentOwner: {fileID: 36699175}
--- !u!95 &96716010

m_Script: {fileID: 11500000, guid: ce2d6128fa5c04c7e84e7978ef8b37a4, type: 3}
m_Name:
m_EditorClassIdentifier:
useDOTS: 1
humanBoat: {fileID: 3457973740146875416, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
aiBoat: {fileID: 980501028647124811, guid: c48ad8112d3b604478deaa848d47c861, type: 3}
raceData:
boats:
- boatName: Boogie

m_OnCameraLive:
m_PersistentCalls:
m_Calls: []
m_TypeName: Cinemachine.CinemachineBrain+VcamActivatedEvent, Cinemachine, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
m_LegacyBlendHint: 0
m_ComponentOwner: {fileID: 141728621}
--- !u!95 &598956453

m_OnCameraLive:
m_PersistentCalls:
m_Calls: []
m_TypeName: Cinemachine.CinemachineBrain+VcamActivatedEvent, Cinemachine, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
m_LegacyBlendHint: 0
m_ComponentOwner: {fileID: 2007948142}
--- !u!95 &674622426

m_OnCameraLive:
m_PersistentCalls:
m_Calls: []
m_TypeName: Cinemachine.CinemachineBrain+VcamActivatedEvent, Cinemachine, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
m_LegacyBlendHint: 0
m_ComponentOwner: {fileID: 1095320328}
--- !u!95 &681645760

m_OnCameraLive:
m_PersistentCalls:
m_Calls: []
m_TypeName: Cinemachine.CinemachineBrain+VcamActivatedEvent, Cinemachine, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
m_LegacyBlendHint: 0
m_ComponentOwner: {fileID: 198446339}
--- !u!1 &1017609894

m_CameraCutEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: Cinemachine.CinemachineBrain+BrainEvent, Cinemachine, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
m_TypeName: Cinemachine.CinemachineBrain+VcamActivatedEvent, Cinemachine, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
--- !u!114 &1017609904
MonoBehaviour:
m_ObjectHideFlags: 0

m_OnCameraLive:
m_PersistentCalls:
m_Calls: []
m_TypeName: Cinemachine.CinemachineBrain+VcamActivatedEvent, Cinemachine, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
m_LegacyBlendHint: 0
m_ComponentOwner: {fileID: 1821796557}
--- !u!95 &1431392952

m_OnCameraLive:
m_PersistentCalls:
m_Calls: []
m_TypeName: Cinemachine.CinemachineBrain+VcamActivatedEvent, Cinemachine, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
m_LegacyBlendHint: 0
m_ComponentOwner: {fileID: 871694112}
--- !u!95 &1881355362

m_OnCameraLive:
m_PersistentCalls:
m_Calls: []
m_TypeName: Cinemachine.CinemachineBrain+VcamActivatedEvent, Cinemachine, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
m_LegacyBlendHint: 0
m_ComponentOwner: {fileID: 1873663219}
--- !u!1001 &6589000189408555943

propertyPath: m_IsActive
value: 1
objectReference: {fileID: 0}
- target: {fileID: 6589000190618102542, guid: e70416e3bc35d4004a9981d0ac102ba5,
type: 3}
propertyPath: m_LocalRotation.y
value: 0.72625333
objectReference: {fileID: 0}
- target: {fileID: 6589000190618102542, guid: e70416e3bc35d4004a9981d0ac102ba5,
type: 3}
propertyPath: m_LocalRotation.w
value: 0.68427867
objectReference: {fileID: 0}
- target: {fileID: 6589000189523060542, guid: e70416e3bc35d4004a9981d0ac102ba5,
type: 3}
propertyPath: m_IsActive

m_SourcePrefab: {fileID: 100100000, guid: e70416e3bc35d4004a9981d0ac102ba5, type: 3}
--- !u!1 &6589000189408555944 stripped
GameObject:
m_CorrespondingSourceObject: {fileID: 1753825905008727154, guid: e70416e3bc35d4004a9981d0ac102ba5,
type: 3}
m_PrefabInstance: {fileID: 6589000189408555943}
m_PrefabAsset: {fileID: 0}
--- !u!114 &6589000189408555945
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6589000189408555944}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: d535e331fdb3f734cb363f09fa881545, type: 3}
m_Name:
m_EditorClassIdentifier:

17
Packages/com.verasl.water-system/Scripts/BuoyantObject.cs


if(_buoyancyType == BuoyancyType.PhysicalVoxel)
{
//Debug.Log("new pass: " + gameObject.name);
UpdateDrag(submergedAmount);
// UpdateDrag(submergedAmount);
}
else if(_buoyancyType == BuoyancyType.Physical)
{

private void BuoyancyForce(Vector3 position, float waterHeight, ref float submergedAmount, ref DebugDrawing _debug)
{
var wp = transform.TransformPoint(position);
float waterLevel = waterHeight;
float waterLevel = waterHeight;
Vector3 force = Vector3.zero;
float k = Mathf.Clamp01((waterLevel - (wp.y - voxelResolution)) / (voxelResolution * 2f));
float k = Mathf.Clamp01((waterLevel - (wp.y - voxelResolution)) / (voxelResolution * 2f));
submergedAmount += k / voxels.Length;//(math.clamp(waterLevel - (wp.y - voxelResolution), 0f, voxelResolution * 2f) / (voxelResolution * 2f)) / voxels.Count;
submergedAmount += k / voxels.Length;//(math.clamp(waterLevel - (wp.y - voxelResolution), 0f, voxelResolution * 2f) / (voxelResolution * 2f)) / voxels.Count;
var force = localDampingForce + Mathf.Sqrt(k) * localArchimedesForce;//\
force = localDampingForce + Mathf.Sqrt(k) * localArchimedesForce;//\
}
}
//Debug.Log(string.Format("Position: {0:f1} -- Force: {1:f2} -- Height: {2:f2}\nVelocty: {3:f2} -- Damp: {4:f2} -- Mass: {5:f1} -- K: {6:f2}", wp, force, waterLevel, velocity, localDampingForce, RB.mass, localArchimedesForce));
}
}
private void UpdateDrag(float submergedAmount)
{

43
Packages/com.verasl.water-system/Scripts/Water.cs


using UnityEngine.Profiling;
using UnityEngine.Rendering;
using UnityEngine.Rendering.LWRP;
using UnityEngine.Rendering.Universal;
using Lightmapping = UnityEngine.Experimental.GlobalIllumination.Lightmapping;
namespace WaterSystem
{

return _Instance;
}
}
// Script references
private MainCameraAlign camAlign;
private PlanarReflections planarReflections;
private bool useComputeBuffer;
public bool computeOverride;

useComputeBuffer = false;
Init();
RenderPipelineManager.beginCameraRendering += BeginCameraRendering;
if(resources == null)
{
resources = Resources.Load("WaterResources") as WaterResources;
}
}
private void OnDisable() {

float roll = cam.transform.localEulerAngles.z;
Shader.SetGlobalFloat("_CameraRoll", roll);
Shader.SetGlobalMatrix("_InvViewProjection", (GL.GetGPUProjectionMatrix(cam.projectionMatrix, false) * cam.worldToCameraMatrix).inverse);
foreach (var mesh in resources.defaultWaterMeshes)
{
Graphics.DrawMesh(mesh, transform.localToWorldMatrix, resources.defaultSeaMaterial, gameObject.layer, cam);
}
}
private void SafeDestroy(Object o)

{
Shader.SetGlobalTexture("_WaterDepthMap", _bakedDepthTex);
}
if (!gameObject.TryGetComponent(out camAlign))
{
camAlign = gameObject.AddComponent<MainCameraAlign>();
camAlign.hideFlags = HideFlags.HideAndDontSave | HideFlags.HideInInspector;
}
if (!gameObject.TryGetComponent(out planarReflections))
{
planarReflections = gameObject.AddComponent<PlanarReflections>();
planarReflections.hideFlags = HideFlags.HideAndDontSave | HideFlags.HideInInspector;
}
planarReflections.m_settings = settingsData.planarSettings;
planarReflections.enabled = settingsData.refType == ReflectionType.PlanarReflection;
if(resources == null)
{
resources = Resources.Load("WaterResources") as WaterResources;
}
//CaptureDepthMap();
private void LateUpdate() {
if(Application.isPlaying)
GerstnerWavesJobs.UpdateHeights();
void Update()
{
waterTime = Time.time;
Shader.SetGlobalFloat("_GlobalTime", waterTime);
GerstnerWavesJobs.UpdateHeights();
}
public void FragWaveNormals(bool toggle)

3
Packages/manifest.json


"com.unity.burst": "1.1.2",
"com.unity.cinemachine": "2.3.4",
"com.unity.collab-proxy": "1.2.16",
"com.unity.entities": "0.1.1-preview",
"com.unity.physics": "0.2.0-preview",
"com.unity.rendering.hybrid": "0.1.1-preview",
"com.unity.test-framework": "1.0.17",
"com.unity.textmeshpro": "2.0.1",
"com.unity.timeline": "1.1.0",

32
ProjectSettings/ProjectSettings.asset


--- !u!129 &1
PlayerSettings:
m_ObjectHideFlags: 0
serializedVersion: 19
serializedVersion: 18
productGUID: b53215438aaf44a9f9817e608bbb159c
AndroidProfiler: 0
AndroidFilterTouchesWhenObscured: 0

m_StackTraceTypes: 010000000100000001000000000000000100000001000000
iosShowActivityIndicatorOnLoading: -1
androidShowActivityIndicatorOnLoading: -1
iosUseCustomAppBackgroundBehavior: 0
iosAppInBackgroundBehavior: 0
iosAllowHTTPDownload: 1
allowedAutorotateToPortrait: 1
allowedAutorotateToPortraitUpsideDown: 1

useMacAppStoreValidation: 0
macAppStoreCategory: public.app-category.games
gpuSkinning: 0
graphicsJobs: 0
xboxPIXTextureCapture: 0
xboxEnableAvatar: 0
xboxEnableKinect: 0

- m_BuildTarget: Android
m_StaticBatching: 1
m_DynamicBatching: 0
m_BuildTargetGraphicsJobs:
- m_BuildTarget: MacStandaloneSupport
m_GraphicsJobs: 1
- m_BuildTarget: Switch
m_GraphicsJobs: 1
- m_BuildTarget: MetroSupport
m_GraphicsJobs: 1
- m_BuildTarget: AppleTVSupport
m_GraphicsJobs: 0
- m_BuildTarget: BJMSupport
m_GraphicsJobs: 1
- m_BuildTarget: LinuxStandaloneSupport
m_GraphicsJobs: 1
- m_BuildTarget: PS4Player
m_GraphicsJobs: 1
- m_BuildTarget: iOSSupport
m_GraphicsJobs: 0
- m_BuildTarget: WindowsStandaloneSupport
m_GraphicsJobs: 1
- m_BuildTarget: XboxOnePlayer
m_GraphicsJobs: 1
- m_BuildTarget: LuminSupport
m_GraphicsJobs: 0
- m_BuildTarget: AndroidPlayer
m_GraphicsJobs: 0
- m_BuildTarget: WebGLSupport
m_GraphicsJobs: 0
m_BuildTargetGraphicsAPIs:
- m_BuildTarget: iOSSupport
m_APIs: 10000000

8
Assets/EntityCache.meta


fileFormatVersion: 2
guid: e50cf0f4dde230944a81a4bb1a939a90
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

8
Assets/Unity Physics Items.meta


fileFormatVersion: 2
guid: b67fc1f9c9fc5be47b5a34feb592f451
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

8
Assets/EntityCache/Resources.meta


fileFormatVersion: 2
guid: f81c7c23b2629154aa90990298a95e36
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
Assets/Unity Physics Items/Physics Scene.unity.meta


fileFormatVersion: 2
guid: 15526d9c33e0e1a4a976cb75b81a90bb
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

8
Assets/Unity Physics Items/Components.meta


fileFormatVersion: 2
guid: abe8179f462907947a719dde0391f6dc
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

8
Assets/Unity Physics Items/Prefabs.meta


fileFormatVersion: 2
guid: a9875aaa1f03515488c4e37f55db9618
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

8
Assets/Unity Physics Items/Systems.meta


fileFormatVersion: 2
guid: 71f78570d6fb8c74a92c6e06b82f20e6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

11
Assets/Unity Physics Items/BuoyantObject_DOTS.cs.meta


fileFormatVersion: 2
guid: 0fe52c158d195e64a99e4eaa38bb3df7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

11
Assets/Unity Physics Items/AIController_DOTS.cs.meta


fileFormatVersion: 2
guid: d535e331fdb3f734cb363f09fa881545
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

15
Assets/Unity Physics Items/BoatBodyComponent.cs


using System.Collections;
using System.Collections.Generic;
using Unity.Entities;
using Unity.Transforms;
using UnityEngine;
public class BoatBodyComponent : MonoBehaviour//, IConvertGameObjectToEntity
{
//Called by parent BuoyantObject_DOTS
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddComponent(entity, typeof(CopyTransformToGameObject));
}
}

375
Assets/Unity Physics Items/BuoyantObject_DOTS.cs


using System;
using System.Collections.Generic;
using UnityEngine;
using Unity.Mathematics;
using Unity.Entities;
using BoatAttack.Boat;
using System.Collections;
//using Unity.Physics;
namespace WaterSystem
{
public class BuoyantObject_DOTS : MonoBehaviour//, IConvertGameObjectToEntity
{
public BuoyancyType _buoyancyType; // type of buoyancy to calculate
public float density; // density of the object, this is calculated off it's volume and mass
public float volume; // volume of the object, this is calculated via it's colliders
public float voxelResolution = 0.51f; // voxel resolution, represents the half size of a voxel when creating the voxel representation
private Bounds voxelBounds; // bounds of the voxels
public Vector3 centerOfMass = Vector3.zero; // Center Of Mass offset
private const float DAMPFER = 0.005f;
private const float WATER_DENSITY = 1000;
private float baseDrag; // reference to original drag
private float baseAngularDrag; // reference to original angular drag
private int _guid; // GUID for the height system
private Vector3 localArchimedesForce;
[SerializeField]
private Vector3[] voxels; // voxel position
private float3[] samplePoints; // sample points for height calc
private float3[] heights; // water height array(only size of 1 when simple or non-physical)
private float3[] normals; // water normal array(only used when non-physical and size of 1 also when simple)
[SerializeField]
Collider[] colliders; // colliders attatched ot this object
Rigidbody RB;
private DebugDrawing[] debugInfo; // For drawing force gizmos
public float percentSubmerged = 0f;
[ContextMenu("Initialize")]
void Init()
{
voxels = null;
if (_buoyancyType == BuoyancyType.NonPhysicalVoxel || _buoyancyType == BuoyancyType.PhysicalVoxel) // If voxel based we need colliders and voxels
{
SetupColliders();
SliceIntoVoxels();
samplePoints = new float3[voxels.Length];
}
if (_buoyancyType == BuoyancyType.Physical || _buoyancyType == BuoyancyType.PhysicalVoxel) // If physical, then we need a rigidbody
{
// The object must have a RidigBody
RB = GetComponent<Rigidbody>();
if (RB == null)
{
RB = gameObject.AddComponent<Rigidbody>();
Debug.LogError(string.Format("Buoyancy:Object \"{0}\" had no Rigidbody. Rigidbody has been added.", name));
}
RB.centerOfMass = centerOfMass + voxelBounds.center;
baseDrag = RB.drag;
baseAngularDrag = RB.angularDrag;
samplePoints = new float3[voxels.Length];
}
if (_buoyancyType == BuoyancyType.NonPhysical || _buoyancyType == BuoyancyType.Physical)
{
voxels = new Vector3[1];
voxels[0] = centerOfMass;
samplePoints = new float3[1];
}
float archimedesForceMagnitude = WATER_DENSITY * -Physics.gravity.y * volume;
localArchimedesForce = new Vector3(0, archimedesForceMagnitude, 0) / samplePoints.Length;
}
private void Start()
{
_guid = gameObject.GetInstanceID();
Init();
if (_buoyancyType == BuoyancyType.NonPhysical || _buoyancyType == BuoyancyType.Physical)
{
debugInfo = new DebugDrawing[1];
heights = new float3[1];// new NativeSlice<float3>();
normals = new float3[1];//new NativeSlice<float3>();
}
else
{
debugInfo = new DebugDrawing[voxels.Length];
heights = new float3[voxels.Length]; //new NativeSlice<float3>();
}
}
void SetupColliders()
{
// The object must have a Collider
colliders = GetComponentsInChildren<Collider>(false);
if (colliders.Length == 0)
{
colliders = new Collider[1];
colliders[0] = gameObject.AddComponent<BoxCollider>();
Debug.LogError(string.Format("Buoyancy:Object \"{0}\" had no coll. BoxCollider has been added.", name));
}
}
void Update()
{
for (var i = 0; i < samplePoints.Length; i++)
{
samplePoints[i] = transform.TransformPoint(voxels[i]);
}
if (_buoyancyType == BuoyancyType.PhysicalVoxel || _buoyancyType == BuoyancyType.Physical) // if acurate the are more points so only heights are needed
{
GerstnerWavesJobs.UpdateSamplePoints(samplePoints, _guid, false);
GerstnerWavesJobs.GetData(_guid, ref heights);
}
else
{
GerstnerWavesJobs.UpdateSamplePoints(samplePoints, _guid, true);
GerstnerWavesJobs.GetSimpleData(_guid, ref heights, ref normals);
if (_buoyancyType == BuoyancyType.NonPhysical)
{
Vector3 vec = transform.position;
vec.y = heights[0].y;
transform.position = vec;
transform.up = Vector3.Slerp(transform.up, normals[0], Time.deltaTime);
}
else if (_buoyancyType == BuoyancyType.NonPhysicalVoxel)
{
// do the voxel non-physical
}
}
}
private void FixedUpdate()
{
float submergedAmount = 0f;
if (_buoyancyType == BuoyancyType.PhysicalVoxel)
{
Physics.autoSyncTransforms = false;
for (var i = 0; i < voxels.Length; i++) BuoyancyForce(voxels[i], heights[i].y, ref submergedAmount, ref debugInfo[i]);
Physics.SyncTransforms();
Physics.autoSyncTransforms = true;
UpdateDrag(submergedAmount);
}
else if (_buoyancyType == BuoyancyType.Physical)
{
BuoyancyForce(Vector3.zero, heights[0].y, ref submergedAmount, ref debugInfo[0]);
UpdateDrag(submergedAmount);
}
}
private void BuoyancyForce(Vector3 position, float waterHeight, ref float submergedAmount, ref DebugDrawing _debug)
{
var wp = transform.TransformPoint(position);
float waterLevel = waterHeight;
_debug.position = wp;
_debug.waterHeight = waterLevel;
_debug.force = Vector3.zero;
if (wp.y - voxelResolution < waterLevel)
{
float k = Mathf.Clamp01(waterLevel - (wp.y - voxelResolution)) / (voxelResolution * 2f);
submergedAmount += k / voxels.Length;//(math.clamp(waterLevel - (wp.y - voxelResolution), 0f, voxelResolution * 2f) / (voxelResolution * 2f)) / voxels.Count;
var velocity = RB.GetPointVelocity(wp);
velocity.y *= 2f;
var localDampingForce = DAMPFER * RB.mass * -velocity;
var force = localDampingForce + Mathf.Sqrt(k) * localArchimedesForce;//\
RB.AddForceAtPosition(force, wp);
_debug.force = force; // For drawing force gizmos
}
}
private void UpdateDrag(float submergedAmount)
{
percentSubmerged = Mathf.Lerp(percentSubmerged, submergedAmount, 0.25f);
RB.drag = baseDrag + (baseDrag * (percentSubmerged * 10f));
RB.angularDrag = baseAngularDrag + (percentSubmerged * 0.5f);
}
private void SliceIntoVoxels()
{
Quaternion rot = transform.rotation;
Vector3 pos = transform.position;
Vector3 size = transform.localScale;
transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
transform.localScale = Vector3.one;
voxels = null;
var points = new List<Vector3>();
var rawBounds = VoxelBounds();
voxelBounds = rawBounds;
voxelBounds.size = RoundVector(rawBounds.size, voxelResolution);
for (float ix = -voxelBounds.extents.x; ix < voxelBounds.extents.x; ix += voxelResolution)
{
for (float iy = -voxelBounds.extents.y; iy < voxelBounds.extents.y; iy += voxelResolution)
{
for (float iz = -voxelBounds.extents.z; iz < voxelBounds.extents.z; iz += voxelResolution)
{
float x = (voxelResolution * 0.5f) + ix;
float y = (voxelResolution * 0.5f) + iy;
float z = (voxelResolution * 0.5f) + iz;
var p = new Vector3(x, y, z) + voxelBounds.center;
bool inside = false;
for (var i = 0; i < colliders.Length; i++)
{
if (PointIsInsideCollider(colliders[i], p))
{
inside = true;
}
}
if (inside)
points.Add(p);
}
}
}
voxels = points.ToArray();
transform.SetPositionAndRotation(pos, rot);
transform.localScale = size;
var voxelVolume = Mathf.Pow(voxelResolution, 3f) * voxels.Length;
var rawVolume = rawBounds.size.x * rawBounds.size.y * rawBounds.size.z;
volume = Mathf.Min(rawVolume, voxelVolume); //actual close to 34.637f
density = gameObject.GetComponent<Rigidbody>().mass / volume;
}
private Bounds VoxelBounds()
{
Bounds bounds = new Bounds();
foreach (Collider nextCollider in colliders)
{
bounds.Encapsulate(nextCollider.bounds);
}
return bounds;
}
static Vector3 RoundVector(Vector3 vec, float rounding)
{
return new Vector3(Mathf.Ceil(vec.x / rounding) * rounding, Mathf.Ceil(vec.y / rounding) * rounding, Mathf.Ceil(vec.z / rounding) * rounding);
}
private bool PointIsInsideCollider(Collider c, Vector3 p)
{
Vector3 cp = Physics.ClosestPoint(p, c, Vector3.zero, UnityEngine.Quaternion.identity);
return Vector3.Distance(cp, p) < 0.01f ? true : false;
}
private void OnDrawGizmosSelected()
{
const float gizmoSize = 0.05f;
var matrix = Matrix4x4.TRS(transform.position, transform.rotation, transform.lossyScale);
Gizmos.matrix = matrix;
if (voxels != null)
{
Gizmos.color = Color.yellow;
foreach (var p in voxels)
{
Gizmos.DrawCube(p, new Vector3(gizmoSize, gizmoSize, gizmoSize));
}
}
if (voxelResolution >= 0.1f)
{
Gizmos.DrawWireCube(voxelBounds.center, voxelBounds.size);
Vector3 center = voxelBounds.center;
float y = center.y - voxelBounds.extents.y;
for (float x = -voxelBounds.extents.x; x < voxelBounds.extents.x; x += voxelResolution)
{
Gizmos.DrawLine(new Vector3(x, y, -voxelBounds.extents.z + center.z), new Vector3(x, y, voxelBounds.extents.z + center.z));
}
for (float z = -voxelBounds.extents.z; z < voxelBounds.extents.z; z += voxelResolution)
{
Gizmos.DrawLine(new Vector3(-voxelBounds.extents.x, y, z + center.z), new Vector3(voxelBounds.extents.x, y, z + center.z));
}
}
else
voxelBounds = VoxelBounds();
Gizmos.color = Color.red;
Gizmos.DrawSphere(voxelBounds.center + centerOfMass, 0.2f);
Gizmos.matrix = Matrix4x4.identity; Gizmos.matrix = Matrix4x4.identity;
if (debugInfo != null)
{
foreach (DebugDrawing debug in debugInfo)
{
Gizmos.color = Color.cyan;
Gizmos.DrawCube(debug.position, new Vector3(gizmoSize, gizmoSize, gizmoSize)); // drawCenter
Vector3 water = debug.position;
water.y = debug.waterHeight;
Gizmos.DrawLine(debug.position, water); // draw the water line
Gizmos.DrawSphere(water, gizmoSize * 4f);
if (_buoyancyType == BuoyancyType.Physical || _buoyancyType == BuoyancyType.PhysicalVoxel)
{
Gizmos.color = Color.red;
Gizmos.DrawRay(debug.position, debug.force / RB.mass); // draw force
}
}
}
}
//Will be called by the PhysicsConversionSystem
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
Init();
BuoyantData data = new BuoyantData();
data.type = _buoyancyType;
data.voxelResolution = voxelResolution;
data.localArchimedesForce = localArchimedesForce;
data.percentSubmerged = 0f;
data.baseDrag = baseDrag;
data.baseAngularDrag = baseAngularDrag;
dstManager.AddComponentData(entity, data);
dstManager.AddBuffer<VoxelOffset>(entity);
dstManager.AddBuffer<VoxelHeight>(entity);
var mass = dstManager.GetComponentData<Unity.Physics.PhysicsMass>(entity);
mass.CenterOfMass = centerOfMass;
dstManager.SetComponentData(entity, mass);
DynamicBuffer<VoxelOffset> offsets = dstManager.GetBuffer<VoxelOffset>(entity);
DynamicBuffer<VoxelHeight> heights = dstManager.GetBuffer<VoxelHeight>(entity);
for (int i = 0; i < voxels.Length; i++)
{
offsets.Add(new VoxelOffset { Value = voxels[i] - centerOfMass });// transform.TransformPoint(voxels[i]) - transform.position }); // << Is this right?
heights.Add(new VoxelHeight { Value = float3.zero });
}
//Call other Convert methods
var body = GetComponentInChildren<BoatBodyComponent>();
body.Convert(conversionSystem.GetPrimaryEntity(body), dstManager, conversionSystem);
var engine = GetComponent<Engine>();
engine.Convert(conversionSystem.GetPrimaryEntity(engine), dstManager, conversionSystem);
}
struct DebugDrawing
{
public Vector3 force;
public Vector3 position;
public float waterHeight;
}
public enum BuoyancyType
{
NonPhysical,
NonPhysicalVoxel,
Physical,
PhysicalVoxel
}
}
}

11
Assets/Unity Physics Items/Components/BoatDataComponents.cs.meta


fileFormatVersion: 2
guid: 5cd1fa5899494974698ae65f8dd12273
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

33
Assets/Unity Physics Items/Components/BoatDataComponents.cs


using Unity.Entities;
using Unity.Mathematics;
using static WaterSystem.BuoyantObject_DOTS;
public struct BuoyantData : IComponentData
{
public BuoyancyType type;
public float voxelResolution;
public float3 normal;
public float3 localArchimedesForce;
public float percentSubmerged;
public float baseDrag;
public float baseAngularDrag;
}
public struct VoxelOffset : IBufferElementData
{
public float3 Value;
}
public struct VoxelHeight : IBufferElementData
{
public float3 Value;
}
public struct DrivingData : IComponentData
{
public bool isHuman;
public float torque;
public float horsePower;
public float3 engineOffset;
public float throttle;
public float steering;
}

11
Assets/Unity Physics Items/Systems/ApplyBuoyancyForceSystem.cs.meta


fileFormatVersion: 2
guid: 6387e875988aca64a81560a89e9386ee
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

11
Assets/Unity Physics Items/Systems/DriveSystem.cs.meta


fileFormatVersion: 2
guid: 0bb75e9b16d3ccf46b42eb1f80cc44b2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

11
Assets/Unity Physics Items/Systems/GertsnerSystem.cs.meta


fileFormatVersion: 2
guid: 54405482a57114844800f64f212d201a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

11
Assets/Unity Physics Items/Systems/PhysicsConversionSystem.cs.meta


fileFormatVersion: 2
guid: 4237fdf5d806beb4388f07fdbdbafe70
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

127
Assets/Unity Physics Items/Systems/GertsnerSystem.cs


using System.Collections;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Physics.Authoring;
using Unity.Transforms;
using UnityEngine;
using WaterSystem;
using WaterSystem.Data;
public class GertsnerSystem : JobComponentSystem
{
private int _waveCount;
private NativeArray<Wave> waveData;
protected override void OnCreate()
{
_waveCount = Water.Instance._waves.Length;
waveData = new NativeArray<Wave>(_waveCount, Allocator.Persistent);
for (var i = 0; i < waveData.Length; i++)
{
waveData[i] = Water.Instance._waves[i];
}
base.OnCreate();
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
var job = new HeightJob {
waveData = waveData,
time = Time.deltaTime,
offsetBuffer = GetBufferFromEntity<VoxelOffset>(false),
heightBuffer = GetBufferFromEntity<VoxelHeight>(false)
};
return job.Schedule(this, inputDeps);
}
[BurstCompile]
public struct HeightJob : IJobForEachWithEntity<Translation, BuoyantData>
{
[ReadOnly]
public NativeArray<Wave> waveData; // wave data stroed in vec4's like the shader version but packed into one
[ReadOnly]
public float time;
[ReadOnly]
public BufferFromEntity<VoxelOffset> offsetBuffer;
[NativeDisableParallelForRestriction]
public BufferFromEntity<VoxelHeight> heightBuffer;
// The code actually running on the job
public void Execute(Entity entity, int i, [ReadOnly] ref Translation translation, ref BuoyantData data)
{
DynamicBuffer<VoxelOffset> offsets = offsetBuffer[entity];
DynamicBuffer<VoxelHeight> heights = heightBuffer[entity];
for (int vi = 0; vi < offsets.Length; vi++)
{
float3 voxelPos = translation.Value + offsets[vi].Value;
var waveCountMulti = 1f / waveData.Length;
float3 wavePos = new float3(0f, 0f, 0f);
float3 waveNorm = new float3(0f, 0f, 0f);
for (var wave = 0; wave < waveData.Length; wave++) // for each wave
{
// Wave data vars
var pos = new float2(voxelPos.x, voxelPos.z);
var amplitude = waveData[wave].amplitude;
var direction = waveData[wave].direction;
var wavelength = waveData[wave].wavelength;
var omniPos = waveData[wave].origin;
////////////////////////////////wave value calculations//////////////////////////
var w = 6.28318f / wavelength; // 2pi over wavelength(hardcoded)
var wSpeed = math.sqrt(9.8f * w); // frequency of the wave based off wavelength
var peak = 0.8f; // peak value, 1 is the sharpest peaks
var qi = peak / (amplitude * w * waveData.Length);
var windDir = new float2(0f, 0f);
var dir = 0f;
direction = math.radians(direction); // convert the incoming degrees to radians
var windDirInput = new float2(math.sin(direction), math.cos(direction)) * (1 - waveData[wave].onmiDir); // calculate wind direction - TODO - currently radians
var windOmniInput = (pos - omniPos) * waveData[wave].onmiDir;
windDir += windDirInput;
windDir += windOmniInput;
windDir = math.normalize(windDir);
dir = math.dot(windDir, pos - (omniPos * waveData[wave].onmiDir)); // calculate a gradient along the wind direction
////////////////////////////position output calculations/////////////////////////
var calc = dir * w + -time * wSpeed; // the wave calculation
var cosCalc = math.cos(calc); // cosine version(used for horizontal undulation)
var sinCalc = math.sin(calc); // sin version(used for vertical undulation)
// calculate the offsets for the current point
wavePos.x += qi * amplitude * windDir.x * cosCalc;
wavePos.z += qi * amplitude * windDir.y * cosCalc;
wavePos.y += ((sinCalc * amplitude)) * waveCountMulti; // the height is divided by the number of waves
if (offsets.Length == 1)
{
////////////////////////////normal output calculations/////////////////////////
float wa = w * amplitude;
// normal vector
float3 norm = new float3(-(windDir.xy * wa * cosCalc),
1 - (qi * wa * sinCalc));
waveNorm += (norm * waveCountMulti) * amplitude;
}
}
heights[vi] = new VoxelHeight{Value = wavePos};
if (offsets.Length == 1)
data.normal = math.normalize(waveNorm.xzy);
}
}
}
}

21
Assets/Unity Physics Items/Systems/PhysicsConversionSystem.cs


using Unity.Entities;
using UnityEngine;
using WaterSystem;
namespace Unity.Physics.Authoring
{
// IConvertGameObjectToEntity pipeline is called before the Physics Body & Shape Conversion Systems
// This means that there would be no Physics components created when Convert was called.
// Instead Convert is called from this specific ConversionSystem for any component that may need
// to read or write the various Physics components at conversion time.
[UpdateAfter(typeof(PhysicsBodyConversionSystem))]
[UpdateAfter(typeof(LegacyRigidbodyConversionSystem))]
public class PhysicsConversionSystem : GameObjectConversionSystem
{
// Update is called once per frame
protected override void OnUpdate()
{
Entities.ForEach((BuoyantObject_DOTS behaviour) => { behaviour.Convert(GetPrimaryEntity(behaviour), DstEntityManager, this); });
}
}
}

96
Assets/Unity Physics Items/Systems/ApplyBuoyancyForceSystem.cs


using System.Collections;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
using static WaterSystem.BuoyantObject_DOTS;
using Unity.Physics.Extensions;
using Unity.Physics.Systems;
using Unity.Physics;
[UpdateAfter(typeof(GertsnerSystem)), UpdateBefore(typeof(BuildPhysicsWorld))]
public class ApplyBuoyancyForceSystem : JobComponentSystem
{
float lastTime = 0;
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
//Debug.Log(string.Format("DeltaTime: {0}, Time.time {1}, Calc Delta: {2}", Time.deltaTime, Time.time, Time.time - lastTime));
//lastTime = Time.time;
var job = new ForceJob()
{
dt = Time.deltaTime,
offsetBuffer = GetBufferFromEntity<VoxelOffset>(false),
heightBuffer = GetBufferFromEntity<VoxelHeight>(false)
};
return job.Schedule(this, inputDeps);
}
//[BurstCompile]
public struct ForceJob : IJobForEachWithEntity<Translation, Rotation, PhysicsVelocity, PhysicsMass, PhysicsDamping, BuoyantData>
{
public float dt;
[ReadOnly]
public BufferFromEntity<VoxelOffset> offsetBuffer;
[ReadOnly]
public BufferFromEntity<VoxelHeight> heightBuffer;
public void Execute(Entity entity, int index, ref Translation pos, ref Rotation rot, ref PhysicsVelocity vel, ref PhysicsMass mass, ref PhysicsDamping damping, ref BuoyantData data)
{
DynamicBuffer<VoxelOffset> offsets = offsetBuffer[entity];
DynamicBuffer<VoxelHeight> heights = heightBuffer[entity];
float submergedAmount = 0f;
//Debug.Log("new pass: " + entity.ToString());
float avgHeight = 0;
int total = 0;
var entityTransform = new RigidTransform(rot.Value, pos.Value);
//Apply buoyant force
for (var i = 0; i < offsets.Length; i++)
{
var wp = math.transform(entityTransform, offsets[i].Value);
float waterLevel = heights[i].Value.y;
if (wp.y - data.voxelResolution < waterLevel)
{
//float depth = waterLevel - wp.y + (data.voxelResolution * 2f);
float subFactor = Mathf.Clamp01((waterLevel - (wp.y - data.voxelResolution)) / (data.voxelResolution * 2f));//depth / data.voxelResolution);
submergedAmount += subFactor / offsets.Length;//(math.clamp(waterLevel - (wp.y - voxelResolution), 0f, voxelResolution * 2f) / (voxelResolution * 2f)) / voxels.Count;
//var force2 = data.localArchimedesForce * subFactor;
var velocity = ComponentExtensions.GetLinearVelocity(vel, mass, pos, rot, wp);
velocity.y *= 2f;
var localDampingForce = .005f * math.rcp(mass.InverseMass) * -velocity;
var force = localDampingForce + math.sqrt(subFactor) * data.localArchimedesForce;//\
ComponentExtensions.ApplyImpulse(ref vel, mass, pos, rot, force * dt, wp);
//entity.ApplyImpulse(force, wp);//RB.AddForceAtPosition(force, wp);
avgHeight += force.y;
total++;
//Debug.Log(string.Format("ECS: Position: {0:f1} -- Force: {1:f2} -- Height: {2:f2}\nVelocty: {3:f2} -- Damp: {4:f2} -- Mass: {5:f1} -- K: {6:f2}", wp, force, waterLevel, velocity, localDampingForce, math.rcp(mass.InverseMass), dt));
}
}
//Update drag
// Debug.Log("Average height: " + avgHeight / total);
//submergedAmount /= offsets.Length;
//damping.Linear = Mathf.Lerp(data.baseDrag, 1f, submergedAmount);
//damping.Angular = Mathf.Lerp(data.baseAngularDrag, 1f, submergedAmount);
data.percentSubmerged = Mathf.Lerp(data.percentSubmerged, submergedAmount, 0.25f);
damping.Linear = data.baseDrag + (data.baseDrag * (data.percentSubmerged * 10f));
damping.Angular = data.baseAngularDrag + (data.percentSubmerged * 0.5f);
}
}
}

68
Assets/Unity Physics Items/Systems/DriveSystem.cs


using System.Collections;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Physics.Extensions;
using Unity.Transforms;
using UnityEngine;
[UpdateAfter(typeof(ApplyBuoyancyForceSystem))]
public class DriveSystem : JobComponentSystem
{
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
var job = new DriveWithInputJob()
{
dt = Time.deltaTime,
};
return job.Schedule(this, inputDeps);
}
[BurstCompile]
public struct DriveWithInputJob : IJobForEachWithEntity<Translation, Rotation, PhysicsVelocity, PhysicsMass, DrivingData>
{
public float dt;
public void Execute(Entity entity, int index, [ReadOnly] ref Translation pos, [ReadOnly] ref Rotation rot, ref PhysicsVelocity vel, [ReadOnly] ref PhysicsMass mass, ref DrivingData data)
{
float velMag = math.dot(vel.Linear, vel.Linear);
var wp = pos.Value + data.engineOffset;
//if (wp.y <= -0.1f) // if the engine is deeper than 0.1
//{
//accel
data.throttle = Mathf.Clamp(data.throttle, 0f, 1f); // clamp for reasonable values
float3 forward = math.forward(rot.Value);
forward.y = 0f;
forward = math.normalize(forward);
var force = (forward * data.throttle * data.horsePower) / mass.InverseMass; //divide by iMass to counteract mass in impulse method
var torque = (data.throttle * new float3(-1, 0, 0)) / mass.InverseInertia;
float3 up = math.mul(rot.Value, math.up());
ComponentExtensions.ApplyLinearImpulse(ref vel, mass, force * dt);
ComponentExtensions.ApplyLinearImpulse(ref vel, mass, up * 20000f * dt);
//ComponentExtensions.ApplyAngularImpulse(ref vel, mass, torque * dt);
//RB.AddForce(forward * modifier * horsePower, ForceMode.Acceleration); // add force forward based on input and horsepower
//RB.AddRelativeTorque(-Vector3.right * modifier, ForceMode.Acceleration);
//Turning
data.steering = Mathf.Clamp(data.steering, -1f, 1f); // clamp for reasonable values
var sTorque = new float3(0f, data.torque, -data.torque * .5f) * data.steering / mass.InverseInertia;
ComponentExtensions.ApplyAngularImpulse(ref vel, mass, sTorque * dt);
//Debug.Log(string.Format("Force: {0}, Torque: {1} Throttle: {2}", force, sTorque, throttle));
//RB.AddRelativeTorque(new Vector3(0f, torque, -torque * 0.5f) * modifier, ForceMode.Acceleration); // add torque based on input and torque amount
//}
}
}
}

54
Assets/Unity Physics Items/Systems/InputSystem.cs


using BoatAttack;
using System.Collections;
using System.Collections.Generic;
using Unity.Entities;
using Unity.Transforms;
using UnityEngine;
[UpdateBefore(typeof(DriveSystem))]
public class InputSystem : ComponentSystem
{
InputControls controls;
float throttle;
float steering;
float startTime;
protected override void OnCreate()
{
startTime = Time.time + WaypointGroup.raceDelay;
controls = new InputControls();
controls.BoatControls.Trottle.performed += context => throttle = context.ReadValue<float>();
controls.BoatControls.Trottle.canceled += context => throttle = 0f;
controls.BoatControls.Steering.performed += context => steering = context.ReadValue<float>();
controls.BoatControls.Steering.canceled += context => steering = 0f;
controls.BoatControls.Enable();
base.OnCreate();
}
protected override void OnUpdate()
{
//not time to start
if (Time.time < startTime)
return;
Entities.ForEach((Entity entity, ref Translation pos, ref Rotation rot, ref DrivingData data ) =>
{
if (data.isHuman)
{
data.throttle = throttle;
data.steering = steering;
}
else
{
AIController_DOTS.GetInputs(entity, pos.Value, rot.Value, out data.throttle, out data.steering);
}
});
}
}

11
Assets/Unity Physics Items/Systems/InputSystem.cs.meta


fileFormatVersion: 2
guid: b8a5f3eb75380dc4b8e643111843c4e9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

11
Assets/Unity Physics Items/BoatBodyComponent.cs.meta


fileFormatVersion: 2
guid: 80b5230fc040dc24a87a4b4792d30957
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

115
Assets/Unity Physics Items/AIController_DOTS.cs


using BoatAttack;
using System.Collections;
using System.Collections.Generic;
using Unity.Entities;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.AI;
class PathData
{
public Vector3[] pathPoint;
public int curPoint;
public int curWP;
public bool foundPath;
};
public class AIController_DOTS : MonoBehaviour
{
static AIController_DOTS main;
Dictionary<Entity, PathData> paths;
private void Awake()
{
if (main != null && main != this)
{
Destroy(this);
return;
}
main = this;
paths = new Dictionary<Entity, PathData>();
}
public static void Register(Entity entity)
{
if (main.paths.ContainsKey(entity))
return;
PathData data = new PathData();
main.paths.Add(entity, data);
}
public static void GetInputs(Entity entity, float3 pos, quaternion rot, out float throttle, out float steering)
{
main.GetInputsInternal(entity, pos, rot, out throttle, out steering);
}
void GetInputsInternal(Entity entity, float3 pos, quaternion rot, out float throttle, out float steering)
{
throttle = steering = 0;
//Do we have data?
PathData data;
if (!paths.TryGetValue(entity, out data))
return;
if (data.pathPoint == null)
{
WaypointGroup.Waypoint wp = WaypointGroup.instance.GetClosestWaypoint(pos);
CalculatePath(WaypointGroup.instance.GetNextWaypoint(wp), data, pos);
}
else if (data.pathPoint.Length > data.curPoint && data.foundPath)
{
if ((Vector3.Distance(pos, data.pathPoint[data.curPoint])) < 8) // If we are close to the current point on the path get the next
{
data.curPoint++; // Move on to next point
if (data.curPoint >= data.pathPoint.Length)
CalculatePath(WaypointGroup.instance.GetWaypoint(data.curWP), data, pos);
}
}
if (data.pathPoint != null && data.pathPoint.Length > data.curPoint)
{
//Get angle to the destination and the side
Vector3 normDir = data.pathPoint[data.curPoint] - (Vector3)pos;
normDir = normDir.normalized;
var forward = math.forward(rot);
float dot = Vector3.Dot(normDir, forward);
//float angle = Mathf.Acos (dot) * Mathf.Rad2Deg;
float targetSide = Vector3.Cross(forward, normDir).y;//positive on right side, negative on left side
steering = Mathf.Clamp(targetSide, -1.0f, 1.0f);
throttle = dot > 0 ? 1f : 0.25f;
}
}
void CalculatePath(WaypointGroup.Waypoint wp, PathData data, float3 pos)
{
var offset = (UnityEngine.Random.value * 2f - 1f) * wp.WPwidth * Vector3.left;
var curWPPos = wp.point + wp.rotation * offset;
data.curWP++;
if (data.curWP >= WaypointGroup.instance.WPs.Count)
data.curWP = 0;
var navPath = new NavMeshPath(); // New nav path
NavMesh.CalculatePath(pos, curWPPos, 255, navPath);
if (navPath.status == NavMeshPathStatus.PathComplete) // if the path is good(complete) use it
{
data.pathPoint = navPath.corners;
data.curPoint = 1;
data.foundPath = true;
}
else if (navPath == null || navPath.status == NavMeshPathStatus.PathInvalid) // if the path is bad, we havent found a path
{
data.foundPath = false;
}
}
}

1001
Assets/Unity Physics Items/Physics Scene.unity
文件差异内容过多而无法显示
查看文件

7
Assets/Unity Physics Items/Prefabs/BoatEntity.prefab.meta


fileFormatVersion: 2
guid: 0a308b87c1579fb4c9ea256406209ca5
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

88
Assets/Unity Physics Items/Prefabs/Physics Settings.prefab


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &6698997538611213016
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4018593011617785703}
- component: {fileID: 1925807081182823211}
- component: {fileID: 6001476266129338508}
- component: {fileID: 4712718218339362870}
m_Layer: 0
m_Name: Physics Settings
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4018593011617785703
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6698997538611213016}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: -81.26014, y: -1.9031935, z: -21.097088}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &1925807081182823211
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6698997538611213016}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 4d30974bf68d61043b1572197db94cdc, type: 3}
m_Name:
m_EditorClassIdentifier:
SimulationType: 1
Gravity:
x: -0
y: -9.81
z: -0
SolverIterationCount: 4
ThreadCountHint: 8
--- !u!114 &6001476266129338508
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6698997538611213016}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: ea7d7495833204790ba1d3a8755397f8, type: 3}
m_Name:
m_EditorClassIdentifier:
ConversionMode: 0
--- !u!114 &4712718218339362870
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6698997538611213016}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: bb54ea4f67dc17342bcd49954c53502d, type: 3}
m_Name:
m_EditorClassIdentifier:
DrawColliders: 1
DrawColliderEdges: 0
DrawColliderAabbs: 0
DrawBroadphase: 0
DrawMassProperties: 1
DrawContacts: 0
DrawCollisionEvents: 0
DrawTriggerEvents: 0
DrawJoints: 0

7
Assets/Unity Physics Items/Prefabs/Physics Settings.prefab.meta


fileFormatVersion: 2
guid: ebb958ca9e119be438b62f3cce1981fc
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

8
Assets/Unity Physics Items/Prefabs/Slippery.asset.meta


fileFormatVersion: 2
guid: 15aa0e33a6fa41749b19f36537af1280
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 0
userData:
assetBundleName:
assetBundleVariant:

42
Assets/Unity Physics Items/Prefabs/Slippery.asset


%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: 11500000, guid: 79f877434772c463192af154345455c9, type: 3}
m_Name: Slippery
m_EditorClassIdentifier:
m_Value:
m_SupportsTemplate: 0
m_Template: {fileID: 0}
m_IsTrigger:
m_Override: 1
m_Value: 0
m_Friction:
m_Override: 1
m_Value:
Value: 0
CombineMode: 0
m_Restitution:
m_Override: 1
m_Value:
Value: 0
CombineMode: 0
m_BelongsTo:
m_Override: 1
m_Value: 0101010101010101010101010101010101010101010101010101010101010101
m_CollidesWith:
m_Override: 1
m_Value: 0101010101010101010101010101010101010101010101010101010101010101
m_RaisesCollisionEvents:
m_Override: 1
m_Value: 0
m_CustomTags:
m_Override: 1
m_Value: 0000000000000000

7
Assets/Unity Physics Items/Prefabs/AIBoatEntity Variant.prefab.meta


fileFormatVersion: 2
guid: c48ad8112d3b604478deaa848d47c861
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

1001
Assets/Unity Physics Items/Prefabs/BoatEntity.prefab
文件差异内容过多而无法显示
查看文件

146
Assets/Unity Physics Items/Prefabs/AIBoatEntity Variant.prefab


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1001 &2478739796189504339
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 3457973740146875416, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_Name
value: AIBoatEntity Variant
objectReference: {fileID: 0}
- target: {fileID: 3457973740146875416, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_IsActive
value: 1
objectReference: {fileID: 0}
- target: {fileID: 3457973740146875417, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalPosition.x
value: -78.9
objectReference: {fileID: 0}
- target: {fileID: 3457973740146875417, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 3457973740146875417, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalPosition.z
value: -20
objectReference: {fileID: 0}
- target: {fileID: 3457973740146875417, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalRotation.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: 3457973740146875417, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalRotation.y
value: 0.95782626
objectReference: {fileID: 0}
- target: {fileID: 3457973740146875417, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: 3457973740146875417, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalRotation.w
value: 0.28734788
objectReference: {fileID: 0}
- target: {fileID: 3457973740146875417, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_RootOrder
value: 0
objectReference: {fileID: 0}
- target: {fileID: 3457973740146875417, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 3457973740146875417, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 3457973740146875417, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6727757724182940452, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: PrimaryColor.r
value: 0.8960905
objectReference: {fileID: 0}
- target: {fileID: 6727757724182940452, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: PrimaryColor.g
value: 0.8960905
objectReference: {fileID: 0}
- target: {fileID: 6727757724182940452, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: PrimaryColor.b
value: 0.8960905
objectReference: {fileID: 0}
- target: {fileID: 6727757724182940452, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: TrimColor.r
value: 0.10390949
objectReference: {fileID: 0}
- target: {fileID: 6727757724182940452, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: TrimColor.g
value: 0.010390951
objectReference: {fileID: 0}
- target: {fileID: 6727757724182940452, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: TrimColor.b
value: 0.030251522
objectReference: {fileID: 0}
- target: {fileID: 6727757724182940452, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: Human
value: 0
objectReference: {fileID: 0}
- target: {fileID: 320792261470743900, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_IsActive
value: 1
objectReference: {fileID: 0}
- target: {fileID: 558137786967539335, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalRotation.x
value: 0.09853761
objectReference: {fileID: 0}
- target: {fileID: 558137786967539335, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalRotation.y
value: -0.0000002682209
objectReference: {fileID: 0}
- target: {fileID: 558137786967539335, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalRotation.z
value: -0.00000011175871
objectReference: {fileID: 0}
- target: {fileID: 558137786967539335, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalPosition.z
value: -5
objectReference: {fileID: 0}
- target: {fileID: 558137786967539335, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalPosition.x
value: 0.0000026226044
objectReference: {fileID: 0}
- target: {fileID: 558137786967539335, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: m_LocalRotation.w
value: 0.99513334
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 0a308b87c1579fb4c9ea256406209ca5, type: 3}
正在加载...
取消
保存