浏览代码

-Added AIControl for dots physics

-Enabled race start from Race Manager
/dots-physics
Mike Geig 5 年前
当前提交
e5796b1b
共有 20 个文件被更改,包括 1454 次插入903 次删除
  1. 6
      Assets/Scripts/Boat/AIcontroller.cs
  2. 2
      Assets/Scripts/Boat/BoatController.cs
  3. 10
      Assets/Scripts/Boat/Engine.cs
  4. 7
      Assets/Scripts/GameSystem/RaceManager.cs
  5. 3
      Assets/Scripts/GameSystem/WaypointGroup.cs
  6. 16
      Assets/Unity Physics Items/BuoyantObject_DOTS.cs
  7. 8
      Assets/Unity Physics Items/Components/BoatDataComponents.cs
  8. 886
      Assets/Unity Physics Items/Physics Scene.unity
  9. 999
      Assets/Unity Physics Items/Prefabs/BoatEntity.prefab
  10. 2
      Assets/Unity Physics Items/Systems/ApplyBuoyancyForceSystem.cs
  11. 43
      Assets/Unity Physics Items/Systems/DriveSystem.cs
  12. 115
      Assets/Unity Physics Items/AIController_DOTS.cs
  13. 11
      Assets/Unity Physics Items/AIController_DOTS.cs.meta
  14. 15
      Assets/Unity Physics Items/BoatBodyComponent.cs
  15. 146
      Assets/Unity Physics Items/Prefabs/AIBoatEntity Variant.prefab
  16. 7
      Assets/Unity Physics Items/Prefabs/AIBoatEntity Variant.prefab.meta
  17. 54
      Assets/Unity Physics Items/Systems/InputSystem.cs
  18. 11
      Assets/Unity Physics Items/Systems/InputSystem.cs.meta
  19. 16
      Assets/Unity Physics Items/Components/BoatBodyComponent.cs
  20. 0
      /Assets/Unity Physics Items/BoatBodyComponent.cs.meta

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>();
Invoke("GetNearestWP", delay);
}
// Update is called once per frame

2
Assets/Scripts/Boat/BoatController.cs


}
// Use this for initialization
void Start()
void Awake()
{
Colourize();
if (Human)

10
Assets/Scripts/Boat/Engine.cs


namespace BoatAttack.Boat
{
public class Engine : MonoBehaviour, IConvertGameObjectToEntity
public class Engine : MonoBehaviour//, IConvertGameObjectToEntity
{
private Rigidbody RB; // The rigid body attatched to the boat
public Vector3 vel; // Boats velocity

Gizmos.DrawCube(enginePosition, new Vector3(0.1f, 0.2f, 0.3f)); // Draw teh engine position with sphere
}
//Called by parent BuoyantObject_DOTS
//Set up driving data
bool isHuman = GetComponent<BoatController>().Human;
if(!isHuman)
AIController_DOTS.Register(entity);
isHuman = isHuman,
torque = torque,
horsePower = horsePower,
engineOffset = transform.TransformPoint(enginePosition) - transform.position

7
Assets/Scripts/GameSystem/RaceManager.cs


}
public Race raceData;
public GameObject humanBoat;
public GameObject aiBoat;
private void OnEnable()
{

foreach (var boat in raceData.boats)
{
var matrix = WaypointGroup.Instance.startingPositons[i];
GameObject boatObject = Instantiate(boat.boatPrefab, matrix.GetColumn(3), Quaternion.LookRotation(matrix.GetColumn(2))) as GameObject;
GameObject boatObject = Instantiate(boat.Human ? humanBoat : aiBoat, matrix.GetColumn(3), Quaternion.LookRotation(matrix.GetColumn(2))) as GameObject;
boatController.Human = boat.Human;
boatController.cam.gameObject.layer = LayerMask.NameToLayer("Player" + (i + 1));
i++;
}

3
Assets/Scripts/GameSystem/WaypointGroup.cs


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

16
Assets/Unity Physics Items/BuoyantObject_DOTS.cs


using UnityEngine;
using Unity.Mathematics;
using Unity.Entities;
using BoatAttack.Boat;
using System.Collections;
//using Unity.Physics;
namespace WaterSystem

}
voxels = points.ToArray();
volume = Mathf.Min(rawVolume, voxelVolume);
volume = Mathf.Min(rawVolume, voxelVolume); //actual close to 34.637f
density = gameObject.GetComponent<Rigidbody>().mass / volume;
}

}
//Will be called by the PhysicsConversionSystem
dstManager.AddComponent(entity, typeof(MoveWithInputTag));
BuoyantData data = new BuoyantData();
data.type = _buoyancyType;

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

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


public struct DrivingData : IComponentData
{
public bool isHuman;
}
public struct MoveWithInputTag : IComponentData
{ }
public float throttle;
public float steering;
}

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

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

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


}
//Update drag
Debug.Log("Average height: " + avgHeight / total);
// 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);

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


[UpdateAfter(typeof(ApplyBuoyancyForceSystem))]
public class DriveSystem : JobComponentSystem
{
InputControls controls;
float throttle;
float steering;
protected override void OnCreate()
{
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();
}
throttle = throttle,
steering = steering
};
return job.Schedule(this, inputDeps);

[RequireComponentTag(typeof(MoveWithInputTag))]
public float throttle;
public float steering;
public void Execute(Entity entity, int index, ref Translation pos, ref Rotation rot, ref PhysicsVelocity vel, ref PhysicsMass mass, ref DrivingData data)
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);

//if (wp.y <= -0.1f) // if the engine is deeper than 0.1
//{
//accel
throttle = Mathf.Clamp(throttle, 0f, 1f); // clamp for reasonable values
data.throttle = Mathf.Clamp(data.throttle, 0f, 1f); // clamp for reasonable values
var force = (forward * throttle * data.horsePower) / mass.InverseMass; //divide by iMass to counteract mass in impulse method
var torque = (throttle * new float3(-1, 0, 0)) / mass.InverseInertia;
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;
//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);
//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);
steering = Mathf.Clamp(steering, -1f, 1f); // clamp for reasonable values
var sTorque = new float3(0f, data.torque, -data.torque * .5f) * steering / mass.InverseInertia;
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

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;
}
}
}

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));
}
}

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: BoatEntity
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.7434182
objectReference: {fileID: 0}
- target: {fileID: 6727757724182940452, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: PrimaryColor.g
value: 0.7434182
objectReference: {fileID: 0}
- target: {fileID: 6727757724182940452, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: PrimaryColor.b
value: 0.7434182
objectReference: {fileID: 0}
- target: {fileID: 6727757724182940452, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: TrimColor.r
value: 0.025658185
objectReference: {fileID: 0}
- target: {fileID: 6727757724182940452, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: TrimColor.g
value: 0.15348418
objectReference: {fileID: 0}
- target: {fileID: 6727757724182940452, guid: 0a308b87c1579fb4c9ea256406209ca5,
type: 3}
propertyPath: TrimColor.b
value: 0.25658178
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: 0
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}

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


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

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:

16
Assets/Unity Physics Items/Components/BoatBodyComponent.cs


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

/Assets/Unity Physics Items/Components/BoatBodyComponent.cs.meta → /Assets/Unity Physics Items/BoatBodyComponent.cs.meta

正在加载...
取消
保存