plantilla base para movimiento básico
This commit is contained in:
Robii Aragon
2026-02-05 05:07:55 -08:00
parent ed7b223c04
commit fd87a6ffd5
14441 changed files with 13711084 additions and 20 deletions

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 7633ebae77a1497479e1047fbfecb9ee
folderAsset: yes
timeCreated: 1518456423
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,347 @@
using System;
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
public class WaypointCircuit : MonoBehaviour
{
public List<Transform> waypointList = new List<Transform> ();
public bool showGizmo;
public Color gizmoLabelColor;
public bool useHandleForVertex;
public bool showVertexHandles;
public Color handleGizmoColor;
public float gizmoRadius;
public float handleRadius;
public bool smoothRoute = true;
int numPoints;
Vector3[] points;
float[] distances;
[Range (1, 100)] public float editorVisualisationSubsteps = 100;
public float Length { get; set; }
//this being here will save GC allocs
int p0n;
int p1n;
int p2n;
int p3n;
float i;
Vector3 P0;
Vector3 P1;
Vector3 P2;
Vector3 P3;
// Use this for initialization
void Awake ()
{
if (waypointList.Count > 1) {
CachePositionsAndDistances ();
}
}
public Vector3 getClosestPosition (Vector3 position)
{
float minDistance = Mathf.Infinity;
int index = -1;
for (int i = 0; i < waypointList.Count; ++i) {
float distance = GKC_Utils.distance (position, waypointList [i].position);
if (distance < minDistance) {
minDistance = distance;
index = i;
}
}
if (index > -1) {
return waypointList [index].position;
} else {
return Vector3.zero;
}
}
public float getProgressValue (Vector3 position)
{
float minDistance = Mathf.Infinity;
int index = -1;
for (int i = 0; i < waypointList.Count; ++i) {
float distance = GKC_Utils.distance (position, waypointList [i].position);
if (distance < minDistance) {
minDistance = distance;
index = i;
}
}
if (index > -1) {
Vector3 closestPosition = waypointList [index].position;
float totalDistance = 0;
if (index > 0) {
Vector3 currentPosition = waypointList [0].position;
for (int i = 1; i < index; ++i) {
float distance = GKC_Utils.distance (currentPosition, waypointList [i].position);
totalDistance += distance;
currentPosition = waypointList [i].position;
}
return totalDistance;
} else {
float distance = GKC_Utils.distance (position, waypointList [0].position);
return distance;
}
}
return -1;
}
public RoutePoint GetRoutePoint (float dist)
{
// position and direction
Vector3 p1 = GetRoutePosition (dist);
Vector3 p2 = GetRoutePosition (dist + 0.1f);
Vector3 delta = p2 - p1;
return new RoutePoint (p1, delta.normalized);
}
public Vector3 GetRoutePosition (float dist)
{
numPoints = waypointList.Count;
int point = 0;
if (Length == 0) {
Length = distances [distances.Length - 1];
}
dist = Mathf.Repeat (dist, Length);
while (distances [point] < dist) {
++point;
}
// get nearest two points, ensuring points wrap-around start & end of circuit
p1n = ((point - 1) + numPoints) % numPoints;
p2n = point;
// found point numbers, now find interpolation value between the two middle points
i = Mathf.InverseLerp (distances [p1n], distances [p2n], dist);
if (smoothRoute) {
// smooth catmull-rom calculation between the two relevant points
// get indices for the surrounding 2 points, because
// four points are required by the catmull-rom function
p0n = ((point - 2) + numPoints) % numPoints;
p3n = (point + 1) % numPoints;
// 2nd point may have been the 'last' point - a dupe of the first,
// (to give a value of max track distance instead of zero)
// but now it must be wrapped back to zero if that was the case.
p2n = p2n % numPoints;
P0 = points [p0n];
P1 = points [p1n];
P2 = points [p2n];
P3 = points [p3n];
return CatmullRom (P0, P1, P2, P3, i);
} else {
// simple linear lerp between the two points:
p1n = ((point - 1) + numPoints) % numPoints;
p2n = point;
return Vector3.Lerp (points [p1n], points [p2n], i);
}
}
Vector3 CatmullRom (Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float i)
{
// comments are no use here... it's the catmull-rom equation.
// Un-magic this, lord vector!
return 0.5f * (2 * p1 + (-p0 + p2) * i + (2 * p0 - 5 * p1 + 4 * p2 - p3) * (i * i) + (-p0 + 3 * p1 - 3 * p2 + p3) * (i * i * i));
}
void CachePositionsAndDistances ()
{
// transfer the position of each point and distances between points to arrays for
// speed of lookup at runtime
points = new Vector3[waypointList.Count + 1];
distances = new float[waypointList.Count + 1];
float accumulateDistance = 0;
for (int i = 0; i < points.Length; ++i) {
Transform t1 = waypointList [(i) % waypointList.Count];
Transform t2 = waypointList [(i + 1) % waypointList.Count];
if (t1 != null && t2 != null) {
Vector3 p1 = t1.position;
Vector3 p2 = t2.position;
points [i] = waypointList [i % waypointList.Count].position;
distances [i] = accumulateDistance;
accumulateDistance += (p1 - p2).magnitude;
}
}
}
public void addNewWayPoint ()
{
Vector3 newPosition = transform.position;
if (waypointList.Count > 0) {
newPosition = waypointList [waypointList.Count - 1].position + waypointList [waypointList.Count - 1].forward;
}
GameObject newWayPoint = new GameObject ();
newWayPoint.transform.SetParent (transform);
newWayPoint.transform.position = newPosition;
newWayPoint.name = (waypointList.Count + 1).ToString ();
waypointList.Add (newWayPoint.transform);
//Undo.RegisterCreatedObjectUndo (newWayPoint, "add new waypoint circuit");
updateComponent ();
}
public void addNewWayPointAtIndex (int index)
{
addNewWayPoint ();
GameObject currentWaypoint = waypointList [waypointList.Count - 1].gameObject;
currentWaypoint.transform.position = waypointList [index].position + waypointList [index].right * 3;
waypointList.Insert ((index + 1), currentWaypoint.transform);
waypointList.RemoveAt (waypointList.Count - 1);
renameWaypoints ();
}
public void renameWaypoints ()
{
for (int i = 0; i < waypointList.Count; ++i) {
waypointList [i].name = (i + 1).ToString ();
waypointList [i].SetParent (null);
waypointList [i].SetParent (transform);
}
updateComponent ();
}
public void resetWaypointsPositions ()
{
Vector3 targetPosition = Vector3.zero;
for (int i = 0; i < waypointList.Count; ++i) {
waypointList [i].localPosition = targetPosition;
targetPosition += Vector3.forward * 2;
}
updateComponent ();
}
public void updateComponent ()
{
GKC_Utils.updateComponent (this);
GKC_Utils.updateDirtyScene ("Update Waypoint Circut System", gameObject);
}
void OnDrawGizmos ()
{
if (!showGizmo) {
return;
}
if (GKC_Utils.isCurrentSelectionActiveGameObject (gameObject)) {
DrawGizmos ();
}
}
void OnDrawGizmosSelected ()
{
DrawGizmos ();
}
void DrawGizmos ()
{
if (showGizmo) {
if (waypointList.Count > 1) {
numPoints = waypointList.Count;
CachePositionsAndDistances ();
Length = distances [distances.Length - 1];
Gizmos.color = gizmoLabelColor;
Vector3 prev = waypointList [0].position;
if (smoothRoute) {
if (editorVisualisationSubsteps <= 0) {
editorVisualisationSubsteps = 1;
}
for (float dist = 0; dist < Length; dist += Length / editorVisualisationSubsteps) {
Vector3 next = GetRoutePosition (dist + 1);
Gizmos.DrawLine (prev, next);
prev = next;
}
Gizmos.DrawLine (prev, waypointList [0].position);
} else {
for (int n = 0; n < waypointList.Count; ++n) {
Vector3 next = waypointList [(n + 1) % waypointList.Count].position;
Gizmos.DrawLine (prev, next);
prev = next;
}
}
}
}
}
public struct RoutePoint
{
public Vector3 position;
public Vector3 direction;
public RoutePoint (Vector3 position, Vector3 direction)
{
this.position = position;
this.direction = direction;
}
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 4cff8e1d60f86284caba64e89c89cdef
timeCreated: 1517514238
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/AI/WaypointCircuit.cs
uploadId: 814740

View File

@@ -0,0 +1,268 @@
using System;
using UnityEngine;
public class WaypointProgressTracker : MonoBehaviour
{
[Header ("Main Settings")]
[Space]
public bool waypointActive;
// This script can be used with any object that is supposed to follow a
// route marked out by waypoints.
// This script manages the amount to look ahead along the route,
// and keeps track of progress and laps.
[SerializeField] float lookAheadForTargetOffset = 5;
// The offset ahead along the route that the we will aim for
[SerializeField] float lookAheadForTargetFactor = .1f;
// A multiplier adding distance ahead along the route to aim for, based on current speed
[SerializeField] float lookAheadForSpeedOffset = 10;
// The offset ahead only the route for speed adjustments (applied as the rotation of the waypoint target transform)
[SerializeField] float lookAheadForSpeedFactor = .2f;
// A multiplier adding distance ahead along the route for speed adjustments
[SerializeField] ProgressStyle progressStyle = ProgressStyle.SmoothAlongRoute;
// whether to update the position smoothly along the route (good for curved paths) or just when we reach each waypoint.
[SerializeField] float pointToPointThreshold = 4;
// proximity to waypoint which must be reached to switch target to next waypoint : only used in PointToPoint mode.
public enum ProgressStyle
{
SmoothAlongRoute,
PointToPoint,
}
// these are public, readable by other objects - i.e. for an AI to know where to head!
public WaypointCircuit.RoutePoint targetPoint { get; set; }
public WaypointCircuit.RoutePoint speedPoint { get; set; }
public WaypointCircuit.RoutePoint progressPoint { get; set; }
[Space]
[Header ("Debug")]
[Space]
public bool showGizmo;
public float progressDistance;
// The progress round the route, used in smooth mode.
public int progressNum;
// the current waypoint number, used in point-to-point mode.
[Space]
[Header ("Components")]
[Space]
public vehicleAINavMesh vehicleAI;
public Transform target;
[SerializeField] WaypointCircuit circuit;
public Transform vehicleTransform;
// A reference to the waypoint-based route we should follow
Vector3 lastPosition;
// Used to calculate current speed (since we may not have a rigidbody component)
float speed;
// current speed of this object (calculated from delta since last frame)
// setup script properties
Transform currentWaypoint;
Vector3 currentVehiclePosition;
void Start ()
{
// we use a transform to represent the point to aim for, and the point which
// is considered for upcoming changes-of-speed. This allows this component
// to communicate this information to the AI without requiring further dependencies.
// You can manually create a transform and assign it to this component *and* the AI,
// then this component will update it, and the AI can read it.
if (waypointActive) {
setTrackActiveState (true);
}
}
public void setWaypointActiveState (bool state)
{
waypointActive = state;
if (waypointActive) {
setTrackActiveState (true);
} else {
setTrackActiveState (false);
}
}
public void activateTrackState ()
{
if (!waypointActive) {
setTrackActiveState (true);
}
}
public void stopTrackState ()
{
if (waypointActive) {
setTrackActiveState (false);
}
}
void setTrackActiveState (bool state)
{
bool circuitLocated = circuit != null;
if (!circuitLocated) {
circuit = FindObjectOfType<WaypointCircuit> ();
circuitLocated = circuit != null;
}
if (!circuitLocated) {
state = false;
waypointActive = false;
}
if (state) {
resetTrackerState ();
if (circuit == null) {
circuit = FindObjectOfType<WaypointCircuit> ();
}
if (vehicleTransform == null) {
vehicleTransform = transform;
}
if (vehicleAI.useNavmeshActive) {
vehicleAI.follow (target);
}
vehicleAI.setDrivingState (true);
vehicleAI.setUsingTrackActive (true);
} else {
vehicleAI.setDrivingState (false);
vehicleAI.setUsingTrackActive (false);
}
}
// reset the object to sensible values
public void resetTrackerState ()
{
bool circuitLocated = circuit != null;
if (!circuitLocated) {
return;
}
if (progressStyle == ProgressStyle.PointToPoint) {
target.position = circuit.waypointList [progressNum].position;
target.rotation = circuit.waypointList [progressNum].rotation;
} else {
target.position = vehicleTransform.position;
target.rotation = vehicleTransform.rotation;
// Vector3 currentPosition = circuit.getClosestPosition (vehicleTransform.position);
// progressDistance = currentPosition.magnitude * 0.5f;
progressDistance = circuit.getProgressValue (vehicleTransform.position);
}
}
void Update ()
{
if (waypointActive) {
currentVehiclePosition = vehicleTransform.position;
if (progressStyle == ProgressStyle.SmoothAlongRoute) {
// determine the position we should currently be aiming for
// (this is different to the current progress position, it is a a certain amount ahead along the route)
// we use lerp as a simple way of smoothing out the speed over time.
if (Time.deltaTime > 0) {
speed = Mathf.Lerp (speed, (lastPosition - currentVehiclePosition).magnitude / Time.deltaTime, Time.deltaTime);
}
target.position = circuit.GetRoutePoint (progressDistance + lookAheadForTargetOffset + lookAheadForTargetFactor * speed).position;
target.rotation = Quaternion.LookRotation (circuit.GetRoutePoint (progressDistance + lookAheadForSpeedOffset + lookAheadForSpeedFactor * speed).direction);
// get our current progress along the route
progressPoint = circuit.GetRoutePoint (progressDistance);
Vector3 progressDelta = progressPoint.position - currentVehiclePosition;
if (Vector3.Dot (progressDelta, progressPoint.direction) < 0) {
progressDistance += progressDelta.magnitude * 0.5f;
}
lastPosition = currentVehiclePosition;
} else {
// point to point mode. Just increase the waypoint if we're close enough:
Vector3 targetDelta = target.position - currentVehiclePosition;
if (targetDelta.magnitude < pointToPointThreshold) {
progressNum = (progressNum + 1) % circuit.waypointList.Count;
}
currentWaypoint = circuit.waypointList [progressNum];
target.position = currentWaypoint.position;
target.rotation = currentWaypoint.rotation;
// get our current progress along the route
progressPoint = circuit.GetRoutePoint (progressDistance);
Vector3 progressDelta = progressPoint.position - currentVehiclePosition;
if (Vector3.Dot (progressDelta, progressPoint.direction) < 0) {
progressDistance += progressDelta.magnitude;
}
lastPosition = currentVehiclePosition;
}
}
}
void OnDrawGizmos ()
{
if (!showGizmo) {
return;
}
if (GKC_Utils.isCurrentSelectionActiveGameObject (gameObject)) {
DrawGizmos ();
}
}
void OnDrawGizmosSelected ()
{
DrawGizmos ();
}
//draw the pivot and the final positions of every door
void DrawGizmos ()
{
if (showGizmo) {
if (Application.isPlaying) {
Gizmos.color = Color.green;
Gizmos.DrawLine (vehicleTransform.position, target.position);
Gizmos.DrawWireSphere (circuit.GetRoutePosition (progressDistance), 1);
Gizmos.color = Color.yellow;
Gizmos.DrawLine (target.position, target.position + target.forward);
}
}
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 33f14a46fbc3b2c4580c014231143423
timeCreated: 1517514238
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/AI/WaypointProgressTracker.cs
uploadId: 814740

View File

@@ -0,0 +1,50 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class remoteVehicleNavmeshOverride : MonoBehaviour
{
[Header ("Main Settings")]
[Space]
public bool targetIsFriendly;
public bool targetIsObject;
public bool setAutoBrakeOnRemoveTargetState;
public bool autoBrakeOnRemoveTarget;
[Space]
[Header ("Components")]
[Space]
public vehicleAINavMesh mainVehicleAINavMesh;
public Transform targetTranform;
public void setVehicleNavMeshTargetPosition ()
{
if (targetTranform == null) {
targetTranform = transform;
}
mainVehicleAINavMesh.follow (targetTranform);
mainVehicleAINavMesh.setTargetType (targetIsFriendly, targetIsObject);
if (setAutoBrakeOnRemoveTargetState) {
mainVehicleAINavMesh.setAutoBrakeOnRemoveTargetState (autoBrakeOnRemoveTarget);
}
}
public void removeVehicleNavmeshTarget ()
{
if (setAutoBrakeOnRemoveTargetState) {
mainVehicleAINavMesh.setAutoBrakeOnRemoveTargetState (autoBrakeOnRemoveTarget);
}
mainVehicleAINavMesh.removeTarget ();
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 159a7fb1c5a257746aef4070a6890cc0
timeCreated: 1678958769
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/AI/remoteVehicleNavmeshOverride.cs
uploadId: 814740

View File

@@ -0,0 +1,810 @@
using System;
using UnityEngine;
using Random = UnityEngine.Random;
using System.Collections;
using System.Collections.Generic;
public class vehicleAINavMesh : AINavMesh
{
[Space]
[Header ("Vehicle AI Navmesh Custom Settings")]
[Space]
public bool vehicleAIActive = true;
public bool useNavmeshActive;
public bool autoBrakeOnRemoveTarget;
[Space]
public bool checkCurrentTargetStateEnabled;
public float checkCurrentTargetStateRate = 0.3f;
[Space]
// This script provides input to the car controller in the same way that the user control script does.
// As such, it is really 'driving' the car, with no special physics or animation tricks to make the car behave properly.
// "wandering" is used to give the cars a more human, less robotic feel. They can waver slightly
// in speed and direction while driving towards their target.
[SerializeField][Range (0, 1)] float m_CautiousSpeedFactor = 0.05f;
// percentage of max speed to use when being maximally cautious
[SerializeField][Range (0, 180)] float m_CautiousMaxAngle = 50f;
// angle of approaching corner to treat as warranting maximum caution
[SerializeField] float m_CautiousMaxDistance = 100f;
// distance at which distance-based cautiousness begins
[SerializeField] float m_CautiousAngularVelocityFactor = 30f;
// how cautious the AI should be when considering its own current angular velocity (i.e. easing off acceleration if spinning!)
[SerializeField] float m_SteerSensitivity = 0.05f;
// how sensitively the AI uses steering input to turn to the desired direction
[SerializeField] float m_AccelSensitivity = 0.04f;
// How sensitively the AI uses the accelerator to reach the current desired speed
[SerializeField] float m_BrakeSensitivity = 1f;
// How sensitively the AI uses the brake to reach the current desired speed
[SerializeField] float m_LateralWanderDistance = 3f;
// how far the car will wander laterally towards its target
[SerializeField] float m_LateralWanderSpeed = 0.1f;
// how fast the lateral wandering will fluctuate
[SerializeField][Range (0, 1)] float m_AccelWanderAmount = 0.1f;
// how much the cars acceleration will wander
[SerializeField] float m_AccelWanderSpeed = 0.1f;
// how fast the cars acceleration wandering will fluctuate
[SerializeField] BrakeCondition m_BrakeCondition = BrakeCondition.TargetDistance;
// what should the AI consider when accelerating/braking?
// whether the AI is currently actively driving or stopped.
// 'target' the target object to aim for.
[SerializeField] bool m_StopWhenTargetReached = false;
// should we stop driving when we reach the target?
[SerializeField] float m_ReachTargetThreshold = 2;
// proximity to target to consider we 'reached' it, and stop driving.
public float maxSpeed;
[Space]
[Header ("Obstacle Detection Settings")]
[Space]
public LayerMask obstacleInFrontLayermask;
public float obstacleInFrontRaycastDistance = 2;
public float obstacleInFrontRaycastOffset = 2;
[Space]
public bool stopIfCertainObstacleLayerDetected;
public LayerMask layermaskToStopIfDetected;
public float capsuleCastRadiusToStopIfDetected;
public float capsuleCastDistanceToStopIfDetected;
[Space]
[Header ("Reverse Direction Settings")]
[Space]
public float reversingAccelereationDuration = 3;
public float minWaitToActivateReversing = 2;
[Space]
[Header ("Debug")]
[Space]
public bool showVehicleDebugPrint;
public Vector2 currentInputValues;
public bool driving;
public bool usingTrackActive;
public bool reversingActiveTemporaly;
public bool obstacleToStopDetected;
[Space]
public bool currentTargetIsCharacter;
public bool currentTargetIsVehicle;
public bool currentTargetIsDriving;
[Space]
[Header ("Components")]
[Space]
public inputActionManager mainInputActionManager;
public Rigidbody m_Rigidbody;
public Transform m_Target;
public Transform vehicleTransform;
public vehicleHUDManager mainVehicleHudManager;
public AIPatrolSystem AIPatrolManager;
float m_RandomPerlin;
// A random value for the car to base its wander on (so that AI cars don't all wander in the same pattern)
float m_AvoidOtherCarTime;
// time until which to avoid the car we recently collided with
float m_AvoidOtherCarSlowdown;
// how much to slow down due to colliding with another car, whilst avoiding
float m_AvoidPathOffset;
// direction (-1 or 1) in which to offset path to avoid other car, whilst avoiding
float currentSpeed;
public enum BrakeCondition
{
NeverBrake,
// the car simply accelerates at full throttle all the time.
TargetDirectionDifference,
// the car will brake according to the upcoming change in direction of the target. Useful for route-based AI, slowing for corners.
TargetDistance,
// the car will brake as it approaches its target, regardless of the target's direction. Useful if you want the car to
// head for a stationary target and come to rest when it arrives there.
}
Vector3 currentVelocity;
Vector2 moveInput;
float cautiousnessRequired;
float spinningAngle;
float lastTimeReversingActive;
float lastTimeReversingDisabled;
float lastSteerDirection = 0;
bool AIPatrolManagerLocated;
float lastTimeCheckCurrentTargetState;
[Space]
[Space]
[TextArea (3, 10)]
public string explanation = "Enable the field Use Navmesh Active on this component if you want to use navmesh on this AI vehicle" +
"instead of the race track system, which is just to follow a group of waypoints.\n\n" +
"The navmesh option allows to set the movement based on the navigation path to reach a target, along with using the AI patrol on" +
"vheicles as well.";
void Awake ()
{
// give the random perlin a random value
m_RandomPerlin = Random.value * 100;
if (m_Rigidbody == null) {
m_Rigidbody = GetComponent<Rigidbody> ();
}
if (vehicleTransform == null) {
vehicleTransform = transform;
}
AIPatrolManagerLocated = AIPatrolManager != null;
}
public override void Start ()
{
base.Start ();
if (gameObject.activeSelf) {
mainVehicleHudManager.setUsedByAIState (true);
}
}
void FixedUpdate ()
{
if (!vehicleAIActive) {
return;
}
if (usingTrackActive) {
updateVehicleTrack ();
}
}
void updateVehicleTrack ()
{
currentVelocity = m_Rigidbody.linearVelocity;
currentSpeed = currentVelocity.magnitude * 2.23693629f;
if (m_Target == null || !driving) {
// Car should not be moving,
// use handbrake to stop
currentInputValues = Vector2.zero;
mainInputActionManager.overrideInputValues (currentInputValues, -1, 1, true);
} else {
Vector3 fwd = vehicleTransform.forward;
if (currentVelocity.magnitude > maxSpeed * 0.1f) {
fwd = currentVelocity;
}
float desiredSpeed = maxSpeed;
// now it's time to decide if we should be slowing down...
switch (m_BrakeCondition) {
case BrakeCondition.TargetDirectionDifference:
// the car will brake according to the upcoming change in direction of the target. Useful for route-based AI, slowing for corners.
// check out the angle of our target compared to the current direction of the car
float approachingCornerAngle = Vector3.Angle (m_Target.forward, fwd);
// also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle
spinningAngle = m_Rigidbody.angularVelocity.magnitude * m_CautiousAngularVelocityFactor;
// if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount
cautiousnessRequired = Mathf.InverseLerp (0, m_CautiousMaxAngle, Mathf.Max (spinningAngle, approachingCornerAngle));
desiredSpeed = Mathf.Lerp (maxSpeed, maxSpeed * m_CautiousSpeedFactor, cautiousnessRequired);
break;
case BrakeCondition.TargetDistance:
// the car will brake as it approaches its target, regardless of the target's direction. Useful if you want the car to
// head for a stationary target and come to rest when it arrives there.
// check out the distance to target
Vector3 delta = Vector3.zero;
if (useNavmeshActive) {
delta = new Vector3 (AIMoveInput.moveInput.x, 0, AIMoveInput.moveInput.z);
} else {
delta = m_Target.position - vehicleTransform.position;
}
float distanceCautiousFactor = Mathf.InverseLerp (m_CautiousMaxDistance, 0, delta.magnitude);
// also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle
spinningAngle = m_Rigidbody.angularVelocity.magnitude * m_CautiousAngularVelocityFactor;
// if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount
cautiousnessRequired = Mathf.Max (Mathf.InverseLerp (0, m_CautiousMaxAngle, spinningAngle), distanceCautiousFactor);
desiredSpeed = Mathf.Lerp (maxSpeed, maxSpeed * m_CautiousSpeedFactor, cautiousnessRequired);
break;
case BrakeCondition.NeverBrake:
break;
}
// Evasive action due to collision with other cars:
// our target position starts off as the 'real' target position
Vector3 offsetTargetPos = m_Target.position;
// if are we currently taking evasive action to prevent being stuck against another car:
if (Time.time < m_AvoidOtherCarTime) {
// slow down if necessary (if we were behind the other car when collision occured)
desiredSpeed *= m_AvoidOtherCarSlowdown;
// and veer towards the side of our path-to-target that is away from the other car
offsetTargetPos += m_AvoidPathOffset * m_Target.right;
} else {
// no need for evasive action, we can just wander across the path-to-target in a random way,
// which can help prevent AI from seeming too uniform and robotic in their driving
offsetTargetPos += ((Mathf.PerlinNoise (Time.time * m_LateralWanderSpeed, m_RandomPerlin) * 2 - 1) * m_LateralWanderDistance) * m_Target.right;
}
// use different sensitivity depending on whether accelerating or braking:
float accelBrakeSensitivity = (desiredSpeed < currentSpeed) ? m_BrakeSensitivity : m_AccelSensitivity;
// decide the actual amount of accel/brake input to achieve desired speed.
float accel = Mathf.Clamp ((desiredSpeed - currentSpeed) * accelBrakeSensitivity, -1, 1);
// add acceleration 'wander', which also prevents AI from seeming too uniform and robotic in their driving
// i.e. increasing the accel wander amount can introduce jostling and bumps between AI cars in a race
accel *= (1 - m_AccelWanderAmount) + (Mathf.PerlinNoise (Time.time * m_AccelWanderSpeed, m_RandomPerlin) * m_AccelWanderAmount);
// calculate the local-relative position of the target, to steer towards
Vector3 localTarget = vehicleTransform.InverseTransformPoint (offsetTargetPos);
// work out the local angle towards the target
float targetAngle = Mathf.Atan2 (localTarget.x, localTarget.z) * Mathf.Rad2Deg;
// get the amount of steering needed to aim the car towards the target
float steer = Mathf.Clamp (targetAngle * m_SteerSensitivity, -1, 1) * Mathf.Sign (currentSpeed);
// feed input to the car controller.
currentInputValues = new Vector2 (steer, accel);
mainInputActionManager.overrideInputValues (currentInputValues, accel, 0, true);
// if appropriate, stop driving when we're close enough to the target.
if (m_StopWhenTargetReached && localTarget.magnitude < m_ReachTargetThreshold) {
setDrivingState (false);
}
}
}
void OnCollisionStay (Collision col)
{
// detect collision against other cars, so that we can take evasive action
if (col.rigidbody != null) {
var otherAI = applyDamage.getVehicle (col.gameObject);
if (otherAI != null) {
// we'll take evasive action for 1 second
m_AvoidOtherCarTime = Time.time + 1;
// but who's in front?...
if (Vector3.Angle (vehicleTransform.forward, otherAI.transform.position - vehicleTransform.position) < 90) {
// the other ai is in front, so it is only good manners that we ought to brake...
m_AvoidOtherCarSlowdown = 0.5f;
} else {
// we're in front! ain't slowing down for anybody...
m_AvoidOtherCarSlowdown = 1;
}
// both cars should take evasive action by driving along an offset from the path centre,
// away from the other car
var otherCarLocalDelta = vehicleTransform.InverseTransformPoint (otherAI.transform.position);
float otherCarAngle = Mathf.Atan2 (otherCarLocalDelta.x, otherCarLocalDelta.z);
m_AvoidPathOffset = m_LateralWanderDistance * -Mathf.Sign (otherCarAngle);
}
}
}
public void enableOrDisableAIObject (bool state)
{
if (state) {
if (!gameObject.activeSelf) {
gameObject.SetActive (state);
pauseAI (false);
setUsedByAIState (state);
}
} else {
if (mainVehicleHudManager.currentDriverIsAI ()) {
return;
}
if (gameObject.activeSelf) {
pauseAI (true);
gameObject.SetActive (state);
setUsedByAIState (state);
mainInputActionManager.overrideInputValues (Vector2.zero, -1, 0, false);
}
}
}
public void enableOrDisableAIObjectWithoutActivatingDrivingState (bool state)
{
if (state) {
if (!gameObject.activeSelf) {
gameObject.SetActive (state);
pauseAI (false);
setUsedByAIStateWithoutActivatingDrvingState (state);
}
} else {
if (mainVehicleHudManager.currentDriverIsAI ()) {
return;
}
if (gameObject.activeSelf) {
pauseAI (true);
gameObject.SetActive (state);
setUsedByAIStateWithoutActivatingDrvingState (state);
mainInputActionManager.overrideInputValues (Vector2.zero, -1, 0, false);
}
}
}
public void setUsedByAIState (bool state)
{
mainVehicleHudManager.setUsedByAIState (state);
}
public void setUsedByAIStateWithoutActivatingDrvingState (bool state)
{
mainVehicleHudManager.setUsedByAIStateWithoutActivatingDrvingState (state);
}
public void enableOrDisablePatrolState (bool state)
{
if (AIPatrolManagerLocated) {
if (state) {
if (!AIPatrolManager.isPatrolPaused ()) {
setPatrolPauseState (false);
AIPatrolManager.setClosestWayPoint ();
AIPatrolManager.setReturningToPatrolState (true);
setTargetType (false, true);
setPatrolState (false);
}
} else {
setPatrolPauseState (true);
setPatrolState (false);
}
}
}
public override void setPatrolTarget (Transform newTarget)
{
if (patrollingPaused) {
return;
}
follow (newTarget);
setTargetType (false, true);
}
public void SetTarget (Transform target)
{
m_Target = target;
setDrivingState (true);
}
public void setDrivingState (bool state)
{
driving = state;
reversingActiveTemporaly = false;
lastSteerDirection = 0;
lastTimeReversingActive = 0;
lastTimeReversingDisabled = 0;
}
public void setUsingTrackActive (bool state)
{
usingTrackActive = state;
}
public void setVehicleAIActiveState (bool state)
{
vehicleAIActive = state;
}
public override void updateAIControllerInputValues ()
{
if (!usingTrackActive) {
if (isFollowingTarget ()) {
Vector3 fwd = vehicleTransform.forward;
if (currentVelocity.magnitude > maxSpeed * 0.1f) {
fwd = currentVelocity;
}
float desiredSpeed = maxSpeed;
Vector3 delta = new Vector3 (AIMoveInput.moveInput.x, 0, AIMoveInput.moveInput.z);
float distanceCautiousFactor = Mathf.InverseLerp (m_CautiousMaxDistance, 0, delta.magnitude);
// also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle
spinningAngle = m_Rigidbody.angularVelocity.magnitude * m_CautiousAngularVelocityFactor;
// if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount
cautiousnessRequired = Mathf.Max (Mathf.InverseLerp (0, m_CautiousMaxAngle, spinningAngle), distanceCautiousFactor);
desiredSpeed = Mathf.Lerp (maxSpeed, maxSpeed * m_CautiousSpeedFactor, cautiousnessRequired);
Vector3 lastPosition = vehicleTransform.position;
// if (canReachCurrentTarget) {
int pathCornersCount = pathCorners.Count;
if (pathCornersCount > 0) {
if (pathCornersCount > 1) {
lastPosition = pathCorners [1];
} else {
lastPosition = pathCorners [0];
}
} else {
if (currentTarget != null) {
lastPosition = currentTarget.position;
}
}
// } else {
//
// }
m_Target.position = lastPosition;
m_Target.rotation = Quaternion.LookRotation (delta);
// Evasive action due to collision with other cars:
// our target position starts off as the 'real' target position
Vector3 offsetTargetPos = m_Target.position;
// if are we currently taking evasive action to prevent being stuck against another car:
if (Time.time < m_AvoidOtherCarTime) {
// slow down if necessary (if we were behind the other car when collision occured)
desiredSpeed *= m_AvoidOtherCarSlowdown;
// and veer towards the side of our path-to-target that is away from the other car
offsetTargetPos += m_AvoidPathOffset * m_Target.right;
} else {
// no need for evasive action, we can just wander across the path-to-target in a random way,
// which can help prevent AI from seeming too uniform and robotic in their driving
offsetTargetPos += ((Mathf.PerlinNoise (Time.time * m_LateralWanderSpeed, m_RandomPerlin) * 2 - 1) * m_LateralWanderDistance) * m_Target.right;
}
// use different sensitivity depending on whether accelerating or braking:
float accelBrakeSensitivity = (desiredSpeed < currentSpeed) ? m_BrakeSensitivity : m_AccelSensitivity;
// decide the actual amount of accel/brake input to achieve desired speed.
float accel = Mathf.Clamp ((desiredSpeed - currentSpeed) * accelBrakeSensitivity, -1, 1);
// add acceleration 'wander', which also prevents AI from seeming too uniform and robotic in their driving
// i.e. increasing the accel wander amount can introduce jostling and bumps between AI cars in a race
accel *= (1 - m_AccelWanderAmount) + (Mathf.PerlinNoise (Time.time * m_AccelWanderSpeed, m_RandomPerlin) * m_AccelWanderAmount);
// calculate the local-relative position of the target, to steer towards
Vector3 localTarget = vehicleTransform.InverseTransformPoint (offsetTargetPos);
// work out the local angle towards the target
float targetAngle = Mathf.Atan2 (localTarget.x, localTarget.z) * Mathf.Rad2Deg;
// get the amount of steering needed to aim the car towards the target
float steer = Mathf.Clamp (targetAngle * m_SteerSensitivity, -1, 1) * Mathf.Sign (currentSpeed);
// feed input to the car controller.
float inputAngleWithVehicle = Vector3.Angle (getDesiredVelocity (), vehicleTransform.forward);
// print (inputAngleWithVehicle);
float inputAngleWithVehicleABS = Math.Abs (inputAngleWithVehicle);
float brakeValue = 0;
if (reversingActiveTemporaly) {
accel *= -1;
if (lastSteerDirection != 0) {
steer = -lastSteerDirection;
}
bool disableReversingResult = false;
if (Time.time > lastTimeReversingActive + reversingAccelereationDuration) {
disableReversingResult = true;
if (showVehicleDebugPrint) {
print ("disabling reversing direction after wait time");
}
}
if (inputAngleWithVehicleABS < 45) {
disableReversingResult = true;
if (showVehicleDebugPrint) {
print ("disabling reversing direction from right angle");
}
}
// print (Math.Abs (inputAngleWithVehicleABS - 180) + " " + Math.Abs (steer) + " " +
// (Math.Abs (steer) < 0.3f) + "" + (Math.Abs (inputAngleWithVehicleABS - 180) < 20));
// Math.Abs (steer) < 0.3f ||
if (lastSteerDirection == 0 && Math.Abs (inputAngleWithVehicleABS - 180) < 10 && Time.time > lastTimeReversingActive + 0.5f) {
disableReversingResult = true;
if (showVehicleDebugPrint) {
print ("disabling reversing direction after movement in opposite direction");
}
}
if (disableReversingResult) {
reversingActiveTemporaly = false;
lastTimeReversingDisabled = Time.time;
lastSteerDirection = 0;
}
} else {
if (lastTimeReversingDisabled == 0 || Time.time > lastTimeReversingDisabled + minWaitToActivateReversing) {
if (inputAngleWithVehicleABS > 70) {
if (checkIfObstacleInFront ()) {
reversingActiveTemporaly = true;
lastTimeReversingActive = Time.time;
if (Math.Abs (steer) > 0.1f) {
lastSteerDirection = steer;
}
if (showVehicleDebugPrint) {
print ("reversing direction from obstacle and direction too off");
}
}
} else if (inputAngleWithVehicleABS > 60 && Mathf.Abs (currentVelocity.magnitude) < 10) {
if (checkIfObstacleInFront ()) {
reversingActiveTemporaly = true;
lastTimeReversingActive = Time.time;
if (Math.Abs (steer) > 0.1f) {
lastSteerDirection = steer;
}
if (showVehicleDebugPrint) {
print ("reversing direction from obstacle and direction too off");
}
}
}
}
if (stopIfCertainObstacleLayerDetected) {
obstacleToStopDetected = checkIfObstacleToStopInFront ();
if (obstacleToStopDetected) {
steer = 0;
accel = 0;
brakeValue = 1;
}
}
}
currentInputValues = new Vector2 (steer, accel);
mainInputActionManager.overrideInputValues (currentInputValues, accel, brakeValue, true);
setOnGroundState (mainVehicleHudManager.isVehicleOnGround ());
} else {
currentInputValues = Vector2.zero;
mainInputActionManager.overrideInputValues (currentInputValues, -1, 1, true);
}
}
if (checkCurrentTargetStateEnabled) {
if (Time.time > lastTimeCheckCurrentTargetState + checkCurrentTargetStateRate) {
checkCurrentTargetState ();
}
}
}
bool checkIfObstacleInFront ()
{
if (Physics.Raycast (vehicleTransform.position + obstacleInFrontRaycastOffset * vehicleTransform.forward,
vehicleTransform.forward, obstacleInFrontRaycastDistance, obstacleInFrontLayermask)) {
return true;
}
return false;
}
bool checkIfObstacleToStopInFront ()
{
Vector3 currentObjectPosition = vehicleTransform.position + obstacleInFrontRaycastOffset * vehicleTransform.forward;
Vector3 targetDirection = vehicleTransform.forward;
Vector3 point1 = currentObjectPosition;
Vector3 point2 = point1 + capsuleCastDistanceToStopIfDetected * targetDirection;
// point1 = currentObjectPosition;
// point2 = currentRayTargetPosition.position + capsuleCastDistanceToStopIfDetected * targetDirection;
RaycastHit [] hits = Physics.CapsuleCastAll (point1, point2, capsuleCastRadiusToStopIfDetected, targetDirection, 0, layermaskToStopIfDetected);
bool surfaceFound = hits.Length > 0;
if (surfaceFound) {
// if (Physics.CapsuleCast (point1, point2, capsuleCastRadiusToStopIfDetected, targetDirection, capsuleCastDistanceToStopIfDetected, layermaskToStopIfDetected)) {
if (showGizmo) {
Debug.DrawLine (point1, point2, Color.red, 2);
}
return true;
} else {
if (showGizmo) {
Debug.DrawLine (point1, point2, Color.green, 2);
}
}
return false;
}
public override void updateAICameraInputValues ()
{
if (!usingTrackActive) {
}
}
public override void removeTarget ()
{
setTarget (null);
if (autoBrakeOnRemoveTarget) {
mainVehicleHudManager.activateAutoBrakeOnGetOff ();
}
}
public override void checkStateOnSetTarget ()
{
checkCurrentTargetState ();
}
void checkCurrentTargetState ()
{
if (checkCurrentTargetStateEnabled) {
if (currentTarget != null) {
currentTargetIsVehicle = applyDamage.isVehicle (currentTarget.gameObject);
currentTargetIsCharacter = applyDamage.isCharacter (currentTarget.gameObject) && !currentTargetIsVehicle;
if (currentTargetIsCharacter) {
currentTargetIsDriving = applyDamage.isCharacterDriving (currentTarget.gameObject);
if (currentTargetIsDriving) {
GameObject currentVehicle = applyDamage.getCharacterCurrentVehicle (currentTarget.gameObject);
if (currentVehicle != null) {
currentTarget = currentVehicle.transform;
currentTargetIsVehicle = true;
currentTargetIsCharacter = false;
if (showDebugPrint) {
print ("update target to vehicle " + currentTarget.name);
}
}
}
} else {
GameObject lastDriverGameObject = applyDamage.getLastDriver (currentTarget.gameObject);
if (lastDriverGameObject != null) {
currentTargetIsDriving = applyDamage.isCharacterDriving (lastDriverGameObject);
if (!currentTargetIsDriving) {
currentTarget = lastDriverGameObject.transform;
currentTargetIsVehicle = false;
currentTargetIsCharacter = true;
if (showDebugPrint) {
print ("update target to character " + currentTarget.name);
}
}
}
}
lastTimeCheckCurrentTargetState = Time.time;
}
}
}
public void setAutoBrakeOnRemoveTargetState (bool state)
{
autoBrakeOnRemoveTarget = state;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: fb47950917292484e9b2b0448d8ba0fe
timeCreated: 1517512879
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/AI/vehicleAINavMesh.cs
uploadId: 814740

View File

@@ -0,0 +1,16 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GKCRiderSocketSystem : MonoBehaviour
{
[Header ("Components")]
[Space]
public mainRiderSystem riderSystem;
public mainRiderSystem getMainRiderSystem ()
{
return riderSystem;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: c27dbad531b360f4fac5de109a194f98
timeCreated: 1638702298
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/GKCRiderSocketSystem.cs
uploadId: 814740

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 0654b1ab17c9dd74bb458c88e8cb32eb
timeCreated: 1633059263
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/GKCSimpleRiderSystem.cs
uploadId: 814740

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: f9f31bc27c19c5d4b9a064b660fdbc6f
timeCreated: 1459365471
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/IKDrivingSystem.cs
uploadId: 814740

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 4ff735fec4ceac24c81ad6852850f178
folderAsset: yes
timeCreated: 1563673030
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 1cec3c6601503804794d4f5a49f6ef9a
timeCreated: 1470351553
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/Vehicle Controllers/airCraftController.cs
uploadId: 814740

View File

@@ -0,0 +1,710 @@
using UnityEngine;
using System.Collections;
using UnityEngine.Events;
public class boatController : vehicleController
{
[Header ("Custom Settings")]
[Space]
public otherVehicleParts vehicleParts;
public vehicleSettings settings;
[Space]
[Header ("Main Settings")]
[Space]
public float moveForwardSpeedMultiplier;
public float moveBackwardSpeedMultiplier;
public float forwardMovementLerpSpeed = 0.8f;
public float airControlAmount;
public float airControlRotationAmount = 4;
public float brakeForce = 5;
public float rollRotationSpeed = 5;
public bool rollRotationReversed;
public float rotationExtraForwardMovement = 0.4f;
public float rotationLerpSpeed = 0.6f;
[Space]
[Header ("Density Settings")]
[Space]
public bool changeDensityEnabled = true;
public float densityChangeAmount = 0.05f;
public Vector2 densityClampValues;
[Space]
[Header ("Orientation Settings")]
[Space]
public float maxAngleRangeForProperOrientationForces = 45;
public bool autoOrientateUpOnWater;
public float minAngleToAutoOrientateUpOnWater;
public float autoOrientateUpForceAmountOnWater;
public bool autoOrientateUpOnAir;
public float minAngleToAutoOrientateUpOnAir;
public float autoOrientateUpForceAmountOnAir;
[Space]
[Header ("Wind Settings")]
[Space]
public bool checkWindState;
public bool sailActive;
public bool ignoreWindForcesIfNotDrivingBoat;
public bool addWindForceIfSailNotActive;
public float windForceMultiplierIfSailNotActive = 0.5f;
public Transform sailTransform;
public Transform sailDirectionTransform;
public float sailWindSpeedMultiplier;
public float sailRotationSpeed;
public float sailRotationClamp;
public float sailRotationAmount;
[Space]
public bool checkBoatOrientationOnWind;
public float maxAngleToReduceSpeedOnIncorrectWindDirection;
public float reduceSpeedOnIncorrectWindDirectionMultiplier;
public bool showWindDirectionObject;
public float windDirectionRotationSpeed;
[Space]
[Header ("Events Settings")]
[Space]
public UnityEvent eventOnActiveWindDetection;
public UnityEvent eventOnDeactiveWindDetection;
public UnityEvent eventOnActiveSail;
public UnityEvent eventOnDeactiveSail;
[Space]
[Header ("Debug")]
[Space]
public bool anyOnGround;
public float normalAngle;
public bool properlyOrientedUp;
public float windAirSpeedMultiplier;
public float windAngle;
public float regularWindAngle;
public bool sailLookingRight;
public Vector3 forceToApply;
public float reducedSpeedOnIncorrectWindMultiplier;
public float boatAngleWithWind;
[Space]
[Header ("Components")]
[Space]
public objectOnWater mainObjectOnWater;
public Transform externalRotationForcePointTransform;
public windOnObjectState mainWindOnObjectState;
public Transform windDirectionTransform;
float originalJumpPower;
Vector3 moveInput;
Transform vehicleCameraTransform;
float rotationToApply;
bool desiredJump;
Vector3 externalRotationForcePoint;
Vector3 totalForceToApply;
float totalRotationToApply;
float forwardInput;
float currentSteeringWheelZAxisAngle;
float currentSailYAxisAngle;
public override void Awake ()
{
base.Awake ();
}
public override void Start ()
{
base.Start ();
originalJumpPower = vehicleControllerSettings.jumpPower;
vehicleCameraTransform = mainVehicleCameraController.transform;
setWindCheckState (checkWindState);
setSailActiveState (sailActive);
}
public override void vehicleUpdate ()
{
base.vehicleUpdate ();
forwardInput = motorInput;
if (!checkWindState) {
if (rotationToApply != 0) {
if (forwardInput == 0) {
forwardInput = rotationExtraForwardMovement;
}
}
}
moveInput = forwardInput * transform.forward;
//+ horizontalAxis * vehicleCameraTransform.right;
moveInput = Vector3.ClampMagnitude (moveInput, 1f);
if (vehicleParts.SteeringWheel != null) {
currentSteeringWheelZAxisAngle =
Mathf.Lerp (currentSteeringWheelZAxisAngle, -vehicleParts.steerAngleLimit * horizontalAxis, Time.deltaTime * vehicleParts.steerRotationSpeed);
if (Mathf.Abs (currentSteeringWheelZAxisAngle) > 0.01f) {
vehicleParts.SteeringWheel.localEulerAngles =
new Vector3 (vehicleParts.SteeringWheel.localEulerAngles.x, vehicleParts.SteeringWheel.localEulerAngles.y, currentSteeringWheelZAxisAngle);
}
}
if (checkWindState) {
if (Mathf.Abs (rawAxisValues.y) > 0) {
if (rawAxisValues.y > 0) {
currentSailYAxisAngle += sailRotationAmount;
} else {
currentSailYAxisAngle -= sailRotationAmount;
}
}
currentSailYAxisAngle = Mathf.Clamp (currentSailYAxisAngle, -sailRotationClamp, sailRotationClamp);
Vector3 eulerTarget = currentSailYAxisAngle * Vector3.up;
Quaternion targetRotation = Quaternion.Euler (eulerTarget);
sailTransform.localRotation = Quaternion.Lerp (sailTransform.localRotation, targetRotation, sailRotationSpeed * Time.deltaTime);
}
}
void FixedUpdate ()
{
if (usingHoverBoardWaypoint) {
return;
}
fixedUpdateVehicle ();
if (checkWindState) {
bool isWindDetected = mainWindOnObjectState.isWindDetected ();
Vector3 windDirection = Vector3.up;
bool canCheckWindForcesResult = true;
if (ignoreWindForcesIfNotDrivingBoat) {
if (!isDrivingActive ()) {
canCheckWindForcesResult = false;
}
}
if (isWindDetected && canCheckWindForcesResult) {
if (sailActive) {
windDirection = mainWindOnObjectState.getwindDirection ();
windAngle = Vector3.SignedAngle (windDirection, sailDirectionTransform.forward, sailDirectionTransform.up);
sailLookingRight = true;
float windAngleABS = Mathf.Abs (windAngle);
// print (sailTransform.localEulerAngles.y);
if (sailTransform.localEulerAngles.y < 180) {
sailLookingRight = false;
}
regularWindAngle = Vector3.Angle (windDirection, sailDirectionTransform.forward);
if (sailLookingRight) {
if (windAngleABS < 90) {
windAirSpeedMultiplier = (sailRotationClamp - regularWindAngle) / sailRotationClamp;
// print ("right and lower 90");
} else {
// print ("right and higher 90");
windAirSpeedMultiplier = (regularWindAngle - sailRotationClamp) / sailRotationClamp;
}
} else {
if (windAngleABS > 90) {
windAirSpeedMultiplier = (regularWindAngle - sailRotationClamp) / sailRotationClamp;
// print ("left and lower 90");
} else {
// print ("left and higher 90");
windAirSpeedMultiplier = (sailRotationClamp - regularWindAngle) / sailRotationClamp;
}
// windAirSpeedMultiplier = (regularWindAngle - sailRotationClamp) / sailRotationClamp;
// windAirSpeedMultiplier = 0;
}
// windAirSpeedMultiplier = regularWindAngle / sailRotationClamp;
windAirSpeedMultiplier = Mathf.Clamp (windAirSpeedMultiplier, 0, 1);
forceToApply = windAirSpeedMultiplier * mainWindOnObjectState.getWindForce () * sailWindSpeedMultiplier * windDirection;
if (checkBoatOrientationOnWind) {
boatAngleWithWind = Vector3.SignedAngle (windDirection, transform.forward, transform.up);
float boatAngleWithWindABS = Mathf.Abs (boatAngleWithWind);
if (boatAngleWithWindABS > maxAngleToReduceSpeedOnIncorrectWindDirection) {
if (boatAngleWithWindABS > 180) {
boatAngleWithWindABS -= 180;
}
reducedSpeedOnIncorrectWindMultiplier = (boatAngleWithWindABS / 180) * reduceSpeedOnIncorrectWindDirectionMultiplier;
forceToApply *= reducedSpeedOnIncorrectWindMultiplier;
}
}
} else {
if (addWindForceIfSailNotActive) {
windDirection = mainWindOnObjectState.getwindDirection ();
forceToApply = mainWindOnObjectState.getWindForce () * windForceMultiplierIfSailNotActive * windDirection;
} else {
forceToApply = Vector3.zero;
}
}
} else {
forceToApply = Vector3.zero;
}
if (showWindDirectionObject) {
if (sailActive) {
Quaternion windDirectionRotationTarget = Quaternion.LookRotation (windDirection);
windDirectionTransform.rotation = Quaternion.Lerp (windDirectionTransform.rotation, windDirectionRotationTarget, Time.deltaTime * windDirectionRotationSpeed);
}
}
}
if (forwardMovementLerpSpeed > 0) {
totalForceToApply = Vector3.Lerp (totalForceToApply, forceToApply, Time.fixedDeltaTime * forwardMovementLerpSpeed);
} else {
totalForceToApply = forceToApply;
}
mainObjectOnWater.updateExternalForces (totalForceToApply, true);
if (rotationLerpSpeed > 0) {
totalRotationToApply = Mathf.Lerp (totalRotationToApply, rotationToApply, Time.fixedDeltaTime * rotationLerpSpeed);
} else {
totalRotationToApply = rotationToApply;
}
float currentRotationSpeed = rollRotationSpeed;
if (!anyOnGround) {
currentRotationSpeed = airControlRotationAmount;
}
mainObjectOnWater.updateExternalRotationForces (totalRotationToApply * currentRotationSpeed,
vehicleCameraTransform.up, externalRotationForcePoint);
currentSpeed = totalForceToApply.magnitude;
}
void fixedUpdateVehicle ()
{
forceToApply = Vector3.zero;
anyOnGround = mainObjectOnWater.isObjectOnWaterActive ();
if (!checkWindState) {
if (anyOnGround) {
if (forwardInput > 0) {
forceToApply = moveForwardSpeedMultiplier * moveInput;
} else if (forwardInput < 0) {
forceToApply = moveBackwardSpeedMultiplier * moveInput;
}
} else {
forceToApply = airControlAmount * moveInput;
}
}
normalAngle = Vector3.SignedAngle (transform.up, mainVehicleGravityControl.getCurrentNormal (), transform.forward);
float normalAngleABS = Mathf.Abs (normalAngle);
properlyOrientedUp = (normalAngleABS < maxAngleRangeForProperOrientationForces);
if (anyOnGround) {
if (autoOrientateUpOnWater) {
if (normalAngleABS > minAngleToAutoOrientateUpOnWater) {
float valueMultiplier = 1;
if (normalAngle > 0) {
valueMultiplier = -1;
}
mainRigidbody.AddRelativeForce (0, 0, autoOrientateUpForceAmountOnWater * valueMultiplier);
}
}
} else {
if (autoOrientateUpOnAir) {
if (normalAngleABS > minAngleToAutoOrientateUpOnAir) {
float valueMultiplier = 1;
if (normalAngle > 0) {
valueMultiplier = -1;
}
mainRigidbody.AddRelativeForce (0, 0, autoOrientateUpForceAmountOnAir * valueMultiplier);
}
}
}
if (!properlyOrientedUp) {
forceToApply = Vector3.zero;
}
if (anyOnGround && properlyOrientedUp) {
if (usingBoost) {
forceToApply *= boostInput;
}
if (desiredJump) {
desiredJump = false;
forceToApply += mainRigidbody.mass * vehicleControllerSettings.jumpPower * vehicleCameraTransform.up;
}
bool brakeActive = (braking || isBrakeActive ());
if (brakeActive) {
float verticalVelocity = vehicleCameraTransform.InverseTransformDirection (mainRigidbody.linearVelocity).y;
Vector3 downVelocity = verticalVelocity * vehicleCameraTransform.up;
mainRigidbody.linearVelocity = Vector3.Lerp (mainRigidbody.linearVelocity, Vector3.zero + downVelocity, Time.deltaTime * brakeForce);
}
}
if (properlyOrientedUp) {
if (rollRotationReversed) {
rotationToApply = horizontalAxis;
} else {
rotationToApply = -horizontalAxis;
}
} else {
rotationToApply = 0;
}
externalRotationForcePoint = externalRotationForcePointTransform.position;
}
public void checkEventOnWindStateChange (bool state)
{
if (state) {
eventOnActiveWindDetection.Invoke ();
} else {
eventOnDeactiveWindDetection.Invoke ();
}
}
public void checkEventOnSailStateChange (bool state)
{
if (state) {
eventOnActiveSail.Invoke ();
} else {
eventOnDeactiveSail.Invoke ();
}
}
public override void updateMovingState ()
{
moving = verticalAxis != 0 || horizontalAxis != 0;
}
public override bool isVehicleOnGround ()
{
return anyOnGround;
}
//if the vehicle is using the gravity control, set the state in this component
public override void changeGravityControlUse (bool state)
{
base.changeGravityControlUse (state);
}
//the player is getting on or off from the vehicle, so
public override void changeVehicleState ()
{
base.changeVehicleState ();
}
public override void setTurnOnState ()
{
}
public override void setTurnOffState (bool previouslyTurnedOn)
{
base.setTurnOffState (previouslyTurnedOn);
if (previouslyTurnedOn) {
}
}
public override bool isDrivingActive ()
{
return driving;
}
public override void setEngineOnOrOffState ()
{
base.setEngineOnOrOffState ();
}
public override void turnOnOrOff (bool state, bool previouslyTurnedOn)
{
base.turnOnOrOff (state, previouslyTurnedOn);
}
//the vehicle has been destroyed, so disabled every component in it
public override void disableVehicle ()
{
base.disableVehicle ();
}
//if the vehicle is using the boost, set the boost particles
public override void usingBoosting ()
{
base.usingBoosting ();
}
//use a jump platform
public void useVehicleJumpPlatform (Vector3 direction)
{
mainRigidbody.AddForce (mainRigidbody.mass * direction, ForceMode.Impulse);
}
public void useJumpPlatformParable (Vector3 direction)
{
Vector3 jumpForce = direction;
mainRigidbody.AddForce (jumpForce, ForceMode.VelocityChange);
}
public void setNewJumpPower (float newJumpPower)
{
vehicleControllerSettings.jumpPower = newJumpPower * 100;
}
public void setOriginalJumpPower ()
{
vehicleControllerSettings.jumpPower = originalJumpPower;
}
public void setCanJumpState (bool state)
{
vehicleControllerSettings.canJump = state;
}
//CALL INPUT FUNCTIONS
public override void inputJump ()
{
if (driving && !usingGravityControl && isTurnedOn && vehicleControllerSettings.canJump) {
if (usingHoverBoardWaypoint) {
pickOrReleaseHoverboardVehicle (false, false);
Vector3 totalJumpForce = mainRigidbody.mass * hoverboardJumpForce * (currentNormal + transform.forward);
if (useHoverboardJumpClamp) {
totalJumpForce = Vector3.ClampMagnitude (totalJumpForce, hoverboardJumpClamp);
}
mainRigidbody.AddForce (totalJumpForce, ForceMode.Impulse);
return;
}
if (anyOnGround) {
desiredJump = true;
}
}
}
public override void inputHoldOrReleaseTurbo (bool holdingButton)
{
if (driving && !usingGravityControl && isTurnedOn && !usingHoverBoardWaypoint) {
//boost input
if (holdingButton) {
if (vehicleControllerSettings.canUseBoost) {
usingBoost = true;
//set the camera move away action
mainVehicleCameraController.usingBoost (true, vehicleControllerSettings.boostCameraShakeStateName,
vehicleControllerSettings.useBoostCameraShake, vehicleControllerSettings.moveCameraAwayOnBoost);
}
} else {
//stop boost input
usingBoost = false;
//disable the camera move away action
mainVehicleCameraController.usingBoost (false, vehicleControllerSettings.boostCameraShakeStateName,
vehicleControllerSettings.useBoostCameraShake, vehicleControllerSettings.moveCameraAwayOnBoost);
usingBoosting ();
boostInput = 1;
}
}
}
public override void inputHoldOrReleaseBrake (bool holdingButton)
{
if (driving && !usingGravityControl && isTurnedOn && anyOnGround) {
braking = holdingButton;
}
}
public override void inputSetTurnOnState ()
{
if (driving && !usingGravityControl) {
if (mainVehicleHUDManager.canSetTurnOnState) {
setEngineOnOrOffState ();
}
}
}
public void setSailActiveState (bool state)
{
sailActive = state;
checkEventOnSailStateChange (sailActive);
}
public void setWindCheckState (bool state)
{
checkWindState = state;
checkEventOnWindStateChange (checkWindState);
}
public void inputToggleWindCheckState ()
{
if (driving) {
setWindCheckState (!checkWindState);
}
}
public void inputToggleSailActive ()
{
if (driving) {
setSailActiveState (!sailActive);
}
}
public void inputIncreaseDensity ()
{
if (driving) {
if (changeDensityEnabled) {
if (mainObjectOnWater.getDensity () < densityClampValues.y) {
mainObjectOnWater.addOrRemoveDensity (densityChangeAmount);
} else {
mainObjectOnWater.setNewDensity (densityClampValues.y);
}
}
}
}
public void inputDecreaseDensity ()
{
if (driving) {
if (changeDensityEnabled) {
if (mainObjectOnWater.getDensity () > densityClampValues.x) {
mainObjectOnWater.addOrRemoveDensity (-densityChangeAmount);
} else {
mainObjectOnWater.setNewDensity (densityClampValues.x);
}
}
}
}
[System.Serializable]
public class otherVehicleParts
{
public Transform COM;
public GameObject chassis;
public Transform SteeringWheel;
public float steerAngleLimit;
public float steerRotationSpeed;
}
[System.Serializable]
public class vehicleSettings
{
public LayerMask layer;
public GameObject vehicleCamera;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: be1d78afc7444b548a9ab7389f5fe36c
timeCreated: 1674660744
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/Vehicle Controllers/boatController.cs
uploadId: 814740

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 238685913253c0843b2b519c6d7786fb
timeCreated: 1461366893
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/Vehicle Controllers/carController.cs
uploadId: 814740

View File

@@ -0,0 +1,8 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class dummyVehicleController : vehicleController
{
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: a6de0571816083c4a9ed9b5f3f089089
timeCreated: 1551942597
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/Vehicle Controllers/dummyVehicleController.cs
uploadId: 814740

View File

@@ -0,0 +1,421 @@
//using UnityEngine;
//using System.Collections;
//using System.Collections.Generic;
//
//public class emptyVehicleController : MonoBehaviour
//{
// public OtherCarParts otherCarParts;
// public carSettings settings;
//
// public float currentSpeed;
//
// public bool anyOnGround;
//
// bool driving;
// bool jump;
// bool colliding;
// bool moving;
// bool usingBoost;
// bool vehicleDestroyed;
// bool usingGravityControl;
//
// float resetTimer = 0;
// float motorInput = 0;
// float steerInput = 0;
// float boostInput = 1;
//
// float horizontalAxis;
// float verticalAxis;
// float originalJumpPower;
// RaycastHit hit;
// Vector3 normal;
// Rigidbody mainRigidbody;
// vehicleCameraController vCamera;
// vehicleHUDManager hudManager;
// inputActionManager actionManager;
// vehicleGravityControl vehicleGravityControlManager;
// shipInterfaceInfo interfaceInfo;
// bool isTurnedOn;
//
// Vector2 axisValues;
// public bool usingImpulse;
// float lastTimeImpulseUsed;
// float lastTimeJump;
//
// bool bouncingVehicle;
// Coroutine bounceCoroutine;
// float collisionForceLimit = 5;
//
// bool braking;
//
// void Start ()
// {
// //set the sound components
// setAudioState (otherCarParts.engineAudio, 5, 0, otherCarParts.engineClip, true, false, false);
// setAudioState (otherCarParts.engineStartAudio, 5, 0.7f, otherCarParts.engineStartClip, false, false, false);
//
// //get the vehicle rigidbody
// mainRigidbody = GetComponent<Rigidbody> ();
//
// vCamera = settings.vehicleCamera.GetComponent<vehicleCameraController> ();
// hudManager = GetComponent<vehicleHUDManager> ();
// originalJumpPower = settings.jumpPower;
// vehicleGravityControlManager = GetComponent<vehicleGravityControl> ();
//
// actionManager = GetComponentInParent<inputActionManager> ();
//
// interfaceInfo = GetComponentInChildren<shipInterfaceInfo> ();
// }
//
// void Update ()
// {
// //if the player is driving this vehicle and the gravity control is not being used, then
// if (driving && !usingGravityControl) {
// axisValues = actionManager.getPlayerMovementAxis ();
// horizontalAxis = axisValues.x;
// if (isTurnedOn) {
//
// //get the current values from the input manager, keyboard and touch controls
// verticalAxis = axisValues.y;
//
// //jump input
//// if (settings.canJump && actionManager.getActionInput ("Jump")) {
//// jump = true;
//// }
//
// //boost input
//// if (settings.canUseBoost && actionManager.getActionInput ("Enable Turbo")) {
//// usingBoost = true;
//// //set the camera move away action
//// vCamera.usingBoost (true, "Boost");
//// }
//
// //stop boost input
//// if (actionManager.getActionInput ("Disable Turbo")) {
//// usingBoost = false;
//// //disable the camera move away action
//// vCamera.usingBoost (false, "Boost");
//// //disable the boost particles
//// boostInput = 1;
//// }
// }
//
// //if the boost input is enabled, check if there is energy enough to use it
// if (usingBoost) {
// //if there is enough energy, enable the boost
// if (hudManager.useBoost (moving)) {
// boostInput = settings.maxBoostMultiplier;
// }
//
// //else, disable the boost
// else {
// usingBoost = false;
// //if the vehicle is not using the gravity control system, disable the camera move away action
// if (!vehicleGravityControlManager.isGravityPowerActive ()) {
// vCamera.usingBoost (false, "Boost");
// }
// boostInput = 1;
// }
// }
//// if (hudManager.canSetTurnOnState && actionManager.getActionInput ("Set TurnOn State")) {
//// setEngineOnOrOffState ();
//// }
////
//// if (actionManager.getActionInput ("Horn")) {
//// pressHorn ();
//// }
////
//// if (actionManager.getActionInput ("Brake")) {
//// braking = true;
//// } else {
//// braking = false;
//// }
//
// //set the current speed in the HUD of the vehicle
// hudManager.getSpeed (currentSpeed, settings.maxForwardSpeed);
// } else {
// //else, set the input values to 0
// horizontalAxis = 0;
// verticalAxis = 0;
// }
//
// if (hudManager.usedByAI) {
// horizontalAxis = vehicleAI.steering;
// verticalAxis = vehicleAI.accel;
// //print (verticalAxis);
// //braking = vehicleAI.footbrake == 1 ? true : false;
// }
//
// //set the current axis input in the motor input
// motorInput = verticalAxis;
// moving = verticalAxis != 0;
//
// //if the vehicle has fuel, allow to move it
// if (moving) {
// if (!hudManager.useFuel ()) {
// motorInput = 0;
// if (isTurnedOn) {
// turnOnOrOff (false, isTurnedOn);
// }
// }
// }
//
// }
//
// public void setEngineOnOrOffState ()
// {
// if (hudManager.hasFuel ()) {
// turnOnOrOff (!isTurnedOn, isTurnedOn);
// }
// }
//
// public void pressHorn ()
// {
// setAudioState (otherCarParts.hornAudio, 5, 1, otherCarParts.hornClip, false, true, false);
// hudManager.activateHorn ();
// }
//
// void FixedUpdate ()
// {
// //allows vehicle to remain roughly pointing in the direction of travel
// //if the vehicle is not on the ground, not colliding, rotating and its speed is higher that 5
// if (!anyOnGround && settings.preserveDirectionWhileInAir && !colliding && currentSpeed > 5) {
// //check the time to stabilize
// //rotate every axis of the vehicle in the rigidbody velocity direction
// mainRigidbody.freezeRotation = true;
// float angleX = Mathf.Asin (transform.InverseTransformDirection (Vector3.Cross (normal.normalized, transform.up)).x) * Mathf.Rad2Deg;
// float angleZ = Mathf.Asin (transform.InverseTransformDirection (Vector3.Cross (normal.normalized, transform.up)).z) * Mathf.Rad2Deg;
// float angleY = Mathf.Asin (transform.InverseTransformDirection (Vector3.Cross (mainRigidbody.velocity.normalized, transform.forward)).y) * Mathf.Rad2Deg;
// transform.Rotate (new Vector3 (angleX, angleY, angleZ) * Time.deltaTime * (-1));
// }
//
// //if any of the vehicle is on the groud, free the rigidbody rotation
// if (anyOnGround) {
// mainRigidbody.freezeRotation = false;
// }
//
// //get the current speed value
// currentSpeed = mainRigidbody.velocity.magnitude * 3;
// //calculate the current acceleration
//
// if (interfaceInfo) {
// interfaceInfo.shipEnginesState (isTurnedOn);
// }
//
// }
//
// //if the vehicle is using the gravity control, set the state in this component
// public void changeGravityControlUse (bool state)
// {
// usingGravityControl = state;
//
// usingImpulse = false;
// }
//
// //the player is getting on or off from the vehicle, so
// //public void changeVehicleState (Vector3 nextPlayerPos)
// public void changeVehicleState ()
// {
// driving = !driving;
// //set the audio values if the player is getting on or off from the vehicle
// if (driving) {
// if (hudManager.autoTurnOnWhenGetOn) {
// turnOnOrOff (true, isTurnedOn);
// }
// } else {
// turnOnOrOff (false, isTurnedOn);
// }
//
// //set the same state in the gravity control components
// vehicleGravityControlManager.changeGravityControlState (driving);
//
// if (interfaceInfo) {
// interfaceInfo.enableOrDisableInterface (driving);
// }
// }
//
// public void setTurnOnState ()
// {
// setAudioState (otherCarParts.engineAudio, 5, 0, otherCarParts.engineClip, true, true, false);
// setAudioState (otherCarParts.engineStartAudio, 5, 0.7f, otherCarParts.engineStartClip, false, true, false);
// }
//
// public void setTurnOffState (bool previouslyTurnedOn)
// {
// if (previouslyTurnedOn) {
// setAudioState (otherCarParts.engineAudio, 5, 0, otherCarParts.engineClip, false, false, true);
// setAudioState (otherCarParts.engineAudio, 5, 1, otherCarParts.engineEndClip, false, true, false);
// }
// motorInput = 0;
// steerInput = 0;
// boostInput = 1;
// horizontalAxis = 0;
// verticalAxis = 0;
//
// //stop the boost
// if (usingBoost) {
// usingBoost = false;
// vCamera.usingBoost (false, "Boost");
//
// }
// usingImpulse = false;
// }
//
// public void turnOnOrOff (bool state, bool previouslyTurnedOn)
// {
// isTurnedOn = state;
// if (isTurnedOn) {
// setTurnOnState ();
// } else {
// setTurnOffState (previouslyTurnedOn);
// }
// }
//
// //the vehicle has been destroyed, so disabled every component in it
// public void disableVehicle ()
// {
// //stop the audio sources
// setAudioState (otherCarParts.engineAudio, 5, 0, otherCarParts.engineClip, false, false, false);
// setAudioState (otherCarParts.engineStartAudio, 5, 0.7f, otherCarParts.engineStartClip, false, false, false);
// vehicleDestroyed = true;
//
// setTurnOffState (false);
//
// //disable the controller
// //GetComponent<carController> ().enabled = false;
//
// if (interfaceInfo) {
// interfaceInfo.enableOrDisableInterface (false);
// }
// }
//
// //get the current normal in the gravity control component
// public void setNormal (Vector3 normalValue)
// {
// normal = normalValue;
// }
//
// //play or stop every audio component in the vehicle, like engine, skid, etc.., configuring also volume and loop according to the movement of the vehicle
// public void setAudioState (AudioSource source, float distance, float volume, AudioClip audioClip, bool loop, bool play, bool stop)
// {
// source.minDistance = distance;
// source.volume = volume;
// source.clip = audioClip;
// source.loop = loop;
// source.spatialBlend = 1;
// if (play) {
// source.Play ();
// }
// if (stop) {
// source.Stop ();
// }
// }
//
// //if any collider in the vehicle collides, then
// void OnCollisionEnter (Collision collision)
// {
// //check that the collision is not with the player
// if (collision.contacts.Length > 0 && collision.gameObject.tag != "Player") {
// //if the velocity of the collision is higher that the limit
// if (collision.relativeVelocity.magnitude > collisionForceLimit) {
// //set the collision audio with a random collision clip
// if (otherCarParts.crashClips.Length > 0) {
// setAudioState (otherCarParts.crashAudio, 5, 1, otherCarParts.crashClips [UnityEngine.Random.Range (0, otherCarParts.crashClips.Length)], false, true, false);
// }
// }
// }
// //reset the collision values
// mainRigidbody.freezeRotation = false;
// colliding = true;
// }
//
// //if the vehicle is colliding, then
// void OnCollisionStay (Collision collision)
// {
// //set the values to avoid stabilize the vehicle yet
// mainRigidbody.freezeRotation = false;
// colliding = true;
// }
//
// //the vehicle is not colliding
// void OnCollisionExit (Collision collision)
// {
// colliding = false;
// }
//
// //use a jump platform
// public void useVehicleJumpPlatform (Vector3 direction)
// {
// mainRigidbody.AddForce (mainRigidbody.mass * direction, ForceMode.Impulse);
// }
//
// public void useJumpPlatformParable (Vector3 direction)
// {
// Vector3 jumpForce = direction;
// print (jumpForce);
// mainRigidbody.AddForce (jumpForce, ForceMode.VelocityChange);
// }
//
// public void setJumpPower (float newJumpPower)
// {
// settings.jumpPower = newJumpPower;
// }
//
// public void setNewJumpPower (float newJumpPower)
// {
// settings.jumpPower = newJumpPower * 100;
// }
//
// public void setOriginalJumpPower ()
// {
// settings.jumpPower = originalJumpPower;
// }
//
// public void setMaxSpeed (float maxSpeedValue)
// {
// settings.maxForwardSpeed = maxSpeedValue;
// }
//
// public void setMaxTurboPower (float maxTurboPower)
// {
// settings.maxBoostMultiplier = maxTurboPower;
// }
//
// vehicleAINavMesh.movementInfo vehicleAI;
//
// public void Move (vehicleAINavMesh.movementInfo AI)
// {
// vehicleAI = AI;
// }
//
// [System.Serializable]
// public class OtherCarParts
// {
// public Transform COM;
// public GameObject chassis;
// public AudioClip engineStartClip;
// public AudioClip engineClip;
// public AudioClip engineEndClip;
// public AudioClip[] crashClips;
// public AudioClip hornClip;
// public AudioSource engineStartAudio;
// public AudioSource engineAudio;
// public AudioSource crashAudio;
// public AudioSource hornAudio;
// }
//
// [System.Serializable]
// public class carSettings
// {
// public LayerMask layer;
//
// public float maxForwardSpeed;
// public float maxBackWardSpeed;
// public float maxBoostMultiplier;
// public GameObject vehicleCamera;
// public bool preserveDirectionWhileInAir;
// public float jumpPower;
// public bool canJump;
// public bool canUseBoost;
// }
//}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: d62013832f03f144fa5c2148c105e499
timeCreated: 1524717024
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/Vehicle Controllers/emptyVehicleController.cs
uploadId: 814740

View File

@@ -0,0 +1,888 @@
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using GameKitController.Audio;
public class flyingController : vehicleController
{
[Header ("Custom Settings")]
[Space]
public float timeToFlip = 2;
public float audioEngineSpeed;
public float engineMinVolume = 0.5f;
public float engineMaxVolume = 1;
public float minAudioPitch = 0.5f;
public float maxAudioPitch = 1.2f;
public float maxSpeed = 30;
public float velocityChangeSpeed = 10;
public float stabilityForce = 2;
public float stabilitySpeed = 2;
public float forwardSpeed = 15;
public float rightSpeed = 15;
public float upSpeed = 15;
public float rollRotationSpeed = 5;
public float engineArmRotationAmountForward;
public float engineArmRotationAmountRight;
public float engineArmExtraRotationAmount;
public float engineArmRotationSpeed;
public float engineRotationSpeed = 10;
public float groundRaycastDistance;
public float hoverForce = 5;
public float hoverFoeceOnAir = 2;
public float rotateForce = 5;
public float extraHoverSpeed = 2;
public bool increaseHeightIfSurfaceBelowFound;
public float raycastDistanceToCheckSurfaceBelow = 5;
public float minDistanceToIncreaseHeight = 4;
public Transform surfaceBelowRaycastPosition;
[Space]
[Header ("Vehicle Settings")]
[Space]
public otherVehicleParts otherCarParts;
public vehicletSettings settings;
[Space]
[Header ("Debug")]
[Space]
public float heightInput;
public float rollDirection;
public bool groundFound;
public Vector3 newVelocity;
[Space]
[Header ("Components")]
[Space]
public Transform leftEngineTransform;
public Transform rightEngineTransform;
public Transform leftEngineArmTransform;
public Transform rightEngineArmTransform;
public Transform groundRaycastPosition;
float audioPower = 0;
float maxEnginePower;
float resetTimer;
float steerInput;
float forwardInput;
int i;
int collisionForceLimit = 5;
bool rotating;
Transform vehicleCameraTransform;
float leftInput = 0;
float rightInput = 0;
bool checkVehicleTurnedOn;
Vector3 currenLeftEngineArmRotation;
Vector3 currenRightEngineArmRotation;
Vector3 currenLeftEngineRotation;
Vector3 currenRightEngineRotation;
Vector3 appliedHoverForce;
RaycastHit hit;
bool usingRollInput;
float currentHitDistance;
bool surfaceDetected;
bool increasingHeightFromSurfaceDetected;
protected override void InitializeAudioElements ()
{
otherCarParts.InitializeAudioElements ();
}
public override void Awake ()
{
base.Awake ();
}
public override void Start ()
{
base.Start ();
//get the boost particles inside the vehicle
for (i = 0; i < otherCarParts.boostingParticles.Count; i++) {
otherCarParts.boostingParticles [i].gameObject.SetActive (false);
}
setAudioState (otherCarParts.engineAudioElement, 5, 0, true, false, false);
setAudioState (otherCarParts.engineStartAudioElement, 5, 0.7f, false, false, false);
vehicleCameraTransform = mainVehicleCameraController.transform;
}
public override void vehicleUpdate ()
{
checkCameraType ();
//if the player is driving this vehicle and the gravity control is not being used, then
if (driving && !usingGravityControl) {
axisValues = mainInputActionManager.getPlayerMovementAxis ();
if (vehicleControllerSettings.canUseBoostWithoutVerticalInput) {
if (usingBoost) {
axisValues.y = 1;
}
}
horizontalAxis = axisValues.x;
if (!playerMovingOn3dWorld) {
horizontalAxis = 0;
}
rawAxisValues = mainInputActionManager.getPlayerRawMovementAxis ();
if (vehicleControllerSettings.canUseBoostWithoutVerticalInput) {
if (usingBoost) {
rawAxisValues.y = 1;
if (!playerMovingOn3dWorld) {
rawAxisValues.x = 1;
}
}
}
if (!useHorizontalInputLerp && !touchPlatform) {
horizontalAxis = rawAxisValues.x;
if (!playerMovingOn3dWorld) {
horizontalAxis = 0;
}
}
if (mainVehicleHUDManager.usedByAI) {
rollDirection = horizontalAxis;
horizontalAxis = 0;
}
if (mainVehicleCameraController.currentState.useCameraSteer && !usingRollInput) {
localLook = transform.InverseTransformDirection (mainVehicleCameraController.getLookDirection ());
if (localLook.z < 0f) {
localLook.x = Mathf.Sign (localLook.x);
}
steering = localLook.x;
steering = Mathf.Clamp (steering, -1f, 1f);
steering = -steering;
rollDirection = steering;
}
if (isTurnedOn) {
//get the current values from the input manager, keyboard and touch controls
verticalAxis = axisValues.y;
if (!playerMovingOn3dWorld) {
verticalAxis = axisValues.x;
}
}
//if the boost input is enabled, check if there is energy enough to use it
if (usingBoost) {
updateMovingState ();
//if there is enough energy, enable the boost
if (mainVehicleHUDManager.useBoost (moving)) {
boostInput = vehicleControllerSettings.maxBoostMultiplier;
usingBoosting ();
}
//else, disable the boost
else {
usingBoost = false;
//if the vehicle is not using the gravity control system, disable the camera move away action
if (!mainVehicleGravityControl.isGravityPowerActive ()) {
mainVehicleCameraController.usingBoost (false, vehicleControllerSettings.boostCameraShakeStateName,
vehicleControllerSettings.useBoostCameraShake, vehicleControllerSettings.moveCameraAwayOnBoost);
}
usingBoosting ();
boostInput = 1;
}
}
//set the current speed in the HUD of the vehicle
mainVehicleHUDManager.getSpeed (currentSpeed, maxSpeed);
mainIKDrivingSystem.setNewAngularDirection (verticalAxis * Vector3.forward +
horizontalAxis * Vector3.right +
heightInput * Vector3.forward +
rollDirection * Vector3.up);
} else {
//else, set the input values to 0
horizontalAxis = 0;
verticalAxis = 0;
rawAxisValues = Vector2.zero;
}
updateMovingState ();
motorInput = verticalAxis;
if (!playerMovingOn3dWorld) {
if (motorInput < -0.01f) {
motorInput *= (-1);
}
}
//if the vehicle has fuel, allow to move it
if (moving) {
if (!mainVehicleHUDManager.useFuel ()) {
motorInput = 0;
if (isTurnedOn) {
turnOnOrOff (false, isTurnedOn);
}
}
}
if (!playerMovingOn3dWorld) {
update2_5DState ();
}
updateVehicleControllerState ();
}
void updateVehicleControllerState ()
{
maxEnginePower = currentSpeed;
audioPower = Mathf.Lerp (maxEnginePower, motorInput, audioEngineSpeed);
otherCarParts.engineAudio.volume = Mathf.Lerp (engineMinVolume, engineMaxVolume, audioPower);
otherCarParts.engineAudio.pitch = Mathf.Lerp (minAudioPitch, maxAudioPitch, audioPower);
if (Mathf.Abs (horizontalAxis) > 0.05f) {
steerInput = Mathf.Lerp (steerInput, horizontalAxis, Time.deltaTime * 10);
} else {
steerInput = Mathf.Lerp (steerInput, horizontalAxis, Time.deltaTime * 10);
}
if (Mathf.Abs (motorInput) > 0.05f) {
forwardInput = Mathf.Lerp (forwardInput, motorInput, Time.deltaTime * 10);
} else {
forwardInput = Mathf.Lerp (forwardInput, motorInput, Time.deltaTime * 10);
}
float left = 0;
float right = 0;
if ((forwardInput > 0.05f || forwardInput < -0.05f) && (steerInput < 0.05f && steerInput > -0.05f)) {
left = right = forwardInput;
//print("moving forward or backward");
} else if (forwardInput > 0.05f && steerInput > 0) {
left = forwardInput;
right = -steerInput;
//print("moving forward and to the right");
} else if (forwardInput > 0.05f && steerInput < 0) {
left = steerInput;
right = forwardInput;
//print("moving forward and to the left");
} else if ((forwardInput < 0.05f && forwardInput > -0.05f) && steerInput > 0) {
left = 0;
right = steerInput;
//print("moving to the right");
} else if ((forwardInput < 0.05f && forwardInput > -0.05f) && steerInput < 0) {
left = -steerInput;
right = 0;
//print("moving to the left");
} else if (forwardInput < -0.05f && steerInput > 0) {
left = 0;
right = -steerInput;
//print("moving backward and to the right");
} else if (forwardInput < -0.05f && steerInput < 0) {
left = steerInput;
right = 0;
//print("moving backward and to the left");
}
leftInput = Mathf.Lerp (leftInput, left, Time.deltaTime * 10);
rightInput = Mathf.Lerp (rightInput, right, Time.deltaTime * 10);
Vector3 rightHandLebarEuler = otherCarParts.rightHandLebar.transform.localEulerAngles;
Vector3 lefttHandLebarEuler = otherCarParts.leftHandLebar.transform.localEulerAngles;
otherCarParts.rightHandLebar.transform.localRotation = Quaternion.Euler (settings.steerAngleLimit * rightInput * 2, rightHandLebarEuler.y, rightHandLebarEuler.z);
otherCarParts.leftHandLebar.transform.localRotation = Quaternion.Euler (settings.steerAngleLimit * leftInput * 2, lefttHandLebarEuler.y, lefttHandLebarEuler.z);
//reset the vehicle rotation if it is upside down
if (currentSpeed < 5) {
//check the current rotation of the vehicle with respect to the normal of the gravity normal component, which always point the up direction
float angle = Vector3.Angle (currentNormal, transform.up);
if (angle > 60 && !rotating) {
resetTimer += Time.deltaTime;
if (resetTimer > timeToFlip) {
resetTimer = 0;
StartCoroutine (rotateVehicle ());
}
}
}
}
void FixedUpdate ()
{
if (!usingGravityControl && isTurnedOn) {
if (usingHoverBoardWaypoint) {
return;
}
surfaceDetected = false;
if (increaseHeightIfSurfaceBelowFound) {
if (Physics.Raycast (surfaceBelowRaycastPosition.position, -transform.up, out hit, raycastDistanceToCheckSurfaceBelow, settings.layer)) {
if (hit.distance < minDistanceToIncreaseHeight) {
increasingHeightFromSurfaceDetected = true;
inputIncreaseHeightState (true);
} else {
if (increasingHeightFromSurfaceDetected) {
inputIncreaseHeightState (false);
increasingHeightFromSurfaceDetected = false;
}
}
} else {
if (increasingHeightFromSurfaceDetected) {
inputIncreaseHeightState (false);
increasingHeightFromSurfaceDetected = false;
}
}
}
if (Physics.Raycast (groundRaycastPosition.position, -transform.up, out hit, groundRaycastDistance, settings.layer)) {
currentHitDistance = hit.distance;
surfaceDetected = true;
}
if (surfaceDetected) {
float proportionalHeight = (groundRaycastDistance - currentHitDistance) / groundRaycastDistance;
appliedHoverForce = (proportionalHeight * hoverForce) * vehicleCameraTransform.up +
((Mathf.Cos (Time.time * extraHoverSpeed)) / 2) * transform.up;
mainVehicleGravityControl.setGravityForcePausedState (false);
groundFound = true;
} else {
if (isTurnedOn) {
mainVehicleGravityControl.setGravityForcePausedState (true);
} else {
mainVehicleGravityControl.setGravityForcePausedState (false);
}
groundFound = false;
}
if (!groundFound) {
if (!moving) {
appliedHoverForce = ((Mathf.Cos (Time.time * extraHoverSpeed)) / 2) * hoverFoeceOnAir * transform.up;
} else {
appliedHoverForce = Vector3.zero;
}
}
if (groundFound && heightInput < 0) {
heightInput = 0;
}
newVelocity = (motorInput * forwardSpeed) * transform.forward +
(horizontalAxis * rightSpeed) * transform.right +
(heightInput * upSpeed) * transform.up;
newVelocity += appliedHoverForce;
newVelocity *= boostInput;
mainRigidbody.linearVelocity = Vector3.Lerp (mainRigidbody.linearVelocity, newVelocity, Time.deltaTime * velocityChangeSpeed);
if (rollDirection != 0) {
transform.Rotate (0, -rollDirection * rollRotationSpeed, 0);
}
Vector3 predictedUp = Quaternion.AngleAxis (mainRigidbody.angularVelocity.magnitude * Mathf.Rad2Deg * stabilityForce / stabilitySpeed, mainRigidbody.angularVelocity) * transform.up;
Vector3 torqueVector = Vector3.Cross (predictedUp, vehicleCameraTransform.up);
mainRigidbody.AddTorque ((stabilitySpeed * stabilitySpeed) * torqueVector);
currentSpeed = mainRigidbody.linearVelocity.magnitude;
currenLeftEngineArmRotation = (heightInput * engineArmRotationAmountForward) * Vector3.forward +
(motorInput * engineArmRotationAmountRight) * Vector3.right -
(horizontalAxis * engineArmRotationAmountForward) * Vector3.forward -
(rollDirection * engineArmRotationAmountRight) * Vector3.right;
currenLeftEngineArmRotation.x =
Mathf.Clamp (currenLeftEngineArmRotation.x, -engineArmRotationAmountRight - engineArmExtraRotationAmount, engineArmRotationAmountRight + engineArmExtraRotationAmount);
currenLeftEngineArmRotation.z =
Mathf.Clamp (currenLeftEngineArmRotation.z, -engineArmRotationAmountForward - engineArmExtraRotationAmount, engineArmRotationAmountForward + engineArmExtraRotationAmount);
leftEngineArmTransform.localRotation =
Quaternion.Lerp (leftEngineArmTransform.localRotation, Quaternion.Euler (currenLeftEngineArmRotation), Time.deltaTime * engineArmRotationSpeed);
currenRightEngineRotation = (-heightInput * engineArmRotationAmountForward) * Vector3.forward +
(motorInput * engineArmRotationAmountRight) * Vector3.right -
(horizontalAxis * engineArmRotationAmountForward) * Vector3.forward +
(rollDirection * engineArmRotationAmountRight) * Vector3.right;
currenRightEngineRotation.x =
Mathf.Clamp (currenRightEngineRotation.x, -engineArmRotationAmountRight - engineArmExtraRotationAmount, engineArmRotationAmountRight + engineArmExtraRotationAmount);
currenRightEngineRotation.z =
Mathf.Clamp (currenRightEngineRotation.z, -engineArmRotationAmountForward - engineArmExtraRotationAmount, engineArmRotationAmountForward + engineArmExtraRotationAmount);
rightEngineArmTransform.localRotation = Quaternion.Lerp (rightEngineArmTransform.localRotation, Quaternion.Euler (currenRightEngineRotation), Time.deltaTime * engineArmRotationSpeed);
rightEngineTransform.Rotate (0, engineRotationSpeed * Time.deltaTime, 0);
leftEngineTransform.Rotate (0, engineRotationSpeed * Time.deltaTime, 0);
}
if (isTurnedOn) {
checkVehicleTurnedOn = true;
//set the exhaust particles state
for (i = 0; i < otherCarParts.normalExhaust.Count; i++) {
if (isTurnedOn && currentSpeed < 20) {
if (!otherCarParts.normalExhaust [i].isPlaying) {
otherCarParts.normalExhaust [i].Play ();
}
} else {
if (otherCarParts.normalExhaust [i].isPlaying) {
otherCarParts.normalExhaust [i].Stop ();
}
}
}
for (i = 0; i < otherCarParts.heavyExhaust.Count; i++) {
if (isTurnedOn && currentSpeed > 10 && motorInput > 0.1f) {
if (!otherCarParts.heavyExhaust [i].isPlaying) {
otherCarParts.heavyExhaust [i].Play ();
}
} else {
if (otherCarParts.heavyExhaust [i].isPlaying) {
otherCarParts.heavyExhaust [i].Stop ();
}
}
}
} else {
if (checkVehicleTurnedOn) {
stopVehicleParticles ();
checkVehicleTurnedOn = false;
}
}
}
//if the vehicle is using the gravity control, set the state in this component
public override void changeGravityControlUse (bool state)
{
base.changeGravityControlUse (state);
}
//the player is getting on or off from the vehicle, so
public override void changeVehicleState ()
{
base.changeVehicleState ();
mainVehicleGravityControl.setGravityForcePausedState (false);
}
public override void setTurnOnState ()
{
setAudioState (otherCarParts.engineAudioElement, 5, 0, true, true, false);
setAudioState (otherCarParts.engineStartAudioElement, 5, 0.7f, false, true, false);
}
public override void setTurnOffState (bool previouslyTurnedOn)
{
base.setTurnOffState (previouslyTurnedOn);
if (previouslyTurnedOn) {
setAudioState (otherCarParts.engineAudioElement, 5, 0, false, false, true);
setAudioState (otherCarParts.engineEndAudioElement, 5, 1, false, true, false);
}
steerInput = 0;
mainVehicleGravityControl.setGravityForcePausedState (false);
}
public override bool isDrivingActive ()
{
return driving;
}
public override void setEngineOnOrOffState ()
{
base.setEngineOnOrOffState ();
}
public override void turnOnOrOff (bool state, bool previouslyTurnedOn)
{
base.turnOnOrOff (state, previouslyTurnedOn);
mainVehicleGravityControl.setCheckDownSpeedActiveState (!isTurnedOn);
}
//the vehicle has been destroyed, so disabled every component in it
public override void disableVehicle ()
{
//stop the audio sources
setAudioState (otherCarParts.engineAudioElement, 5, 0, false, false, false);
setAudioState (otherCarParts.engineStartAudioElement, 5, 0.7f, false, false, false);
setTurnOffState (false);
//disable the exhausts particles
stopVehicleParticles ();
//disable the controller
this.enabled = false;
}
public void stopVehicleParticles ()
{
for (i = 0; i < otherCarParts.normalExhaust.Count; i++) {
otherCarParts.normalExhaust [i].Stop ();
}
for (i = 0; i < otherCarParts.heavyExhaust.Count; i++) {
otherCarParts.heavyExhaust [i].Stop ();
}
for (int i = 0; i < otherCarParts.boostingParticles.Count; i++) {
var boostingParticlesMain = otherCarParts.boostingParticles [i].main;
boostingParticlesMain.loop = false;
}
}
//reset the vehicle rotation if it is upside down
IEnumerator rotateVehicle ()
{
rotating = true;
Quaternion currentRotation = transform.rotation;
//rotate in the forward direction of the vehicle
Quaternion dstRotPlayer = Quaternion.LookRotation (transform.forward, currentNormal);
for (float t = 0; t < 1;) {
t += Time.deltaTime * 3;
transform.rotation = Quaternion.Slerp (currentRotation, dstRotPlayer, t);
mainRigidbody.linearVelocity = Vector3.zero;
yield return null;
}
rotating = false;
}
//if the vehicle is using the boost, set the boost particles
public override void usingBoosting ()
{
base.usingBoosting ();
for (int i = 0; i < otherCarParts.boostingParticles.Count; i++) {
if (usingBoost) {
if (!otherCarParts.boostingParticles [i].isPlaying) {
otherCarParts.boostingParticles [i].gameObject.SetActive (true);
otherCarParts.boostingParticles [i].Play ();
var boostingParticlesMain = otherCarParts.boostingParticles [i].main;
boostingParticlesMain.loop = true;
}
} else {
if (otherCarParts.boostingParticles [i].isPlaying) {
var boostingParticlesMain = otherCarParts.boostingParticles [i].main;
boostingParticlesMain.loop = false;
}
}
}
}
//OVERRIDE FUNCTIONS FOR VEHICLE CONTROLLER
//if any collider in the vehicle collides, then
public override void setCollisionDetected (Collision currentCollision)
{
//check that the collision is not with the player
if (!currentCollision.gameObject.CompareTag ("Player")) {
//if the velocity of the collision is higher that the limit
if (currentCollision.relativeVelocity.magnitude > collisionForceLimit) {
//set the collision audio with a random collision clip
if (otherCarParts.crashAudioElements.Length > 0) {
setAudioState (otherCarParts.crashAudioElements [UnityEngine.Random.Range (0, otherCarParts.crashAudioElements.Length)], 5, 1, false, true, false);
}
}
}
}
public override void startBrakeVehicleToStopCompletely ()
{
}
public override void endBrakeVehicleToStopCompletely ()
{
}
public override float getCurrentSpeed ()
{
return currentSpeed;
}
public override void updateMovingState ()
{
moving = verticalAxis != 0 || horizontalAxis != 0 || heightInput != 0 || rollDirection != 0;
}
//CALL INPUT FUNCTIONS
public override void inputHoldOrReleaseTurbo (bool holdingButton)
{
if (driving && !usingGravityControl && isTurnedOn && !usingHoverBoardWaypoint) {
//boost input
if (holdingButton) {
usingBoost = true;
//set the camera move away action
mainVehicleCameraController.usingBoost (true, vehicleControllerSettings.boostCameraShakeStateName,
vehicleControllerSettings.useBoostCameraShake, vehicleControllerSettings.moveCameraAwayOnBoost);
} else {
//stop boost
usingBoost = false;
//disable the camera move away action
mainVehicleCameraController.usingBoost (false, vehicleControllerSettings.boostCameraShakeStateName,
vehicleControllerSettings.useBoostCameraShake, vehicleControllerSettings.moveCameraAwayOnBoost);
//disable the boost particles
usingBoosting ();
boostInput = 1;
}
}
}
public override void inputSetTurnOnState ()
{
if (driving && !usingGravityControl) {
if (mainVehicleHUDManager.canSetTurnOnState) {
setEngineOnOrOffState ();
}
}
}
public override void inputHorn ()
{
if (driving) {
setAudioState (otherCarParts.hornAudioElement, 5, 1, false, true, false);
}
}
public void inputIncreaseHeightState (bool state)
{
if (driving && !usingGravityControl && isTurnedOn) {
if (state) {
if (usingHoverBoardWaypoint) {
pickOrReleaseHoverboardVehicle (false, false);
Vector3 totalJumpForce = mainRigidbody.mass * hoverboardJumpForce * (currentNormal + transform.forward);
if (useHoverboardJumpClamp) {
totalJumpForce = Vector3.ClampMagnitude (totalJumpForce, hoverboardJumpClamp);
}
mainRigidbody.AddForce (totalJumpForce, ForceMode.Impulse);
return;
}
}
if (state) {
heightInput = 1;
} else {
heightInput = 0;
}
}
}
public void inputDecreaseHeightState (bool state)
{
if (driving && !usingGravityControl && isTurnedOn) {
if (state) {
heightInput = -1;
} else {
heightInput = 0;
}
}
}
public void inputSetRotateToLeftState (bool state)
{
if (driving && isTurnedOn) {
if (!playerMovingOn3dWorld) {
rollDirection = 0;
usingRollInput = false;
return;
}
if (state) {
rollDirection = 1;
} else {
rollDirection = 0;
}
usingRollInput = state;
}
}
public void inputSetRotateToRightState (bool state)
{
if (driving && isTurnedOn) {
if (!playerMovingOn3dWorld) {
rollDirection = 0;
usingRollInput = false;
return;
}
if (state) {
rollDirection = -1;
} else {
rollDirection = 0;
}
usingRollInput = state;
}
}
[System.Serializable]
public class otherVehicleParts
{
public Transform rightHandLebar;
public Transform leftHandLebar;
public Transform COM;
public GameObject chassis;
public AudioClip engineStartClip;
public AudioElement engineStartAudioElement;
public AudioClip engineClip;
public AudioElement engineAudioElement;
public AudioClip engineEndClip;
public AudioElement engineEndAudioElement;
public AudioClip[] crashClips;
public AudioElement[] crashAudioElements;
public AudioClip hornClip;
public AudioElement hornAudioElement;
public List<ParticleSystem> normalExhaust = new List<ParticleSystem> ();
public List<ParticleSystem> heavyExhaust = new List<ParticleSystem> ();
public AudioSource engineStartAudio;
public AudioSource engineAudio;
public AudioSource crashAudio;
public AudioSource hornAudio;
public List<ParticleSystem> boostingParticles = new List<ParticleSystem> ();
public void InitializeAudioElements ()
{
if (engineStartClip != null) {
engineStartAudioElement.clip = engineStartClip;
}
if (engineClip != null) {
engineAudioElement.clip = engineClip;
}
if (engineEndClip != null) {
engineEndAudioElement.clip = engineEndClip;
}
if (crashClips != null && crashClips.Length > 0) {
crashAudioElements = new AudioElement[crashClips.Length];
for (var i = 0; i < crashClips.Length; i++) {
crashAudioElements [i] = new AudioElement { clip = crashClips [i] };
}
}
if (hornClip != null) {
hornAudioElement.clip = hornClip;
}
if (engineStartAudio != null) {
engineStartAudioElement.audioSource = engineStartAudio;
}
if (engineAudio != null) {
engineAudioElement.audioSource = engineAudio;
engineEndAudioElement.audioSource = engineAudio;
}
if (crashAudio != null) {
foreach (var audioElement in crashAudioElements) {
audioElement.audioSource = crashAudio;
}
}
if (hornAudio != null) {
hornAudioElement.audioSource = hornAudio;
}
}
}
[System.Serializable]
public class vehicletSettings
{
public LayerMask layer;
public float steerAngleLimit;
public float increaseHeightSpeed = 2;
public float decreaseHeightSpeed = 2;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 78778710b85e18a4691e7fe44ef4983a
timeCreated: 1551571300
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/Vehicle Controllers/flyingController.cs
uploadId: 814740

View File

@@ -0,0 +1,210 @@
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class hoverBoardAnimationSystem : MonoBehaviour
{
[Header ("Main Settings")]
[Space]
public float extraBodyRotation = -20;
public float extraSpineRotation = 30;
public float limitBodyRotationX = 30;
public float limitBodyRotationZ = 30;
public float minSpineRotationX = 20;
public float maxSpineRotationX = 330;
public float maxArmsRotation = 25;
public bool addMovementToBody;
public bool addExtraMovementToBody;
public bool addMovementToArms;
public bool addMovementToHead;
public float maxHeadRotationBackward;
public float headRotationSpeed;
public float minBackwardVelocityToHeadRotation;
[Space]
[Header ("Components")]
[Space]
public Transform headLookCenter;
public Transform bodyLookCenter;
public Transform bodyLookPivot;
public Rigidbody mainRigidbody;
public hoverBoardController mainHoverBoardController;
public Transform hoverBoardTransform;
public Transform playerGravityCenter;
upperBodyRotationSystem mainUpperBodyRotationSystem;
Vector3 currentNormal;
float gravityCenterAngleX;
float gravityCenterAngleZ;
float angleZ;
float currentExtraBodyRotation;
float currentExtraSpineRotation;
float headLookCenterCurrentRotation;
bool driving;
Animator animator;
Transform rightArm;
Transform leftArm;
bool firstPersonActive;
bool animationActive;
void Start ()
{
currentExtraBodyRotation = extraBodyRotation;
currentExtraSpineRotation = extraSpineRotation;
}
void Update ()
{
if (driving) {
firstPersonActive = mainHoverBoardController.firstPersonActive;
if (!firstPersonActive && animationActive) {
currentNormal = mainHoverBoardController.getNormal ();
currentNormal = currentNormal.normalized;
angleZ = Mathf.Asin (hoverBoardTransform.InverseTransformDirection (Vector3.Cross (currentNormal, hoverBoardTransform.up)).z) * Mathf.Rad2Deg;
float angleX = Mathf.Asin (hoverBoardTransform.InverseTransformDirection (Vector3.Cross (currentNormal, hoverBoardTransform.up)).x) * Mathf.Rad2Deg;
float gravityAngleZ = 0;
if (Mathf.Abs (angleZ) > 1) {
gravityAngleZ = -angleZ;
} else {
gravityAngleZ = 0;
}
float gravityAngleX = 0;
if (Mathf.Abs (angleX) > 1) {
gravityAngleX = -angleX;
} else {
gravityAngleX = 0;
}
gravityCenterAngleX = Mathf.Lerp (gravityCenterAngleX, gravityAngleX, Time.deltaTime * 5);
gravityCenterAngleZ = Mathf.Lerp (gravityCenterAngleZ, gravityAngleZ, Time.deltaTime * 5);
gravityCenterAngleX = Mathf.Clamp (gravityCenterAngleX, -limitBodyRotationX, limitBodyRotationX);
gravityCenterAngleZ = Mathf.Clamp (gravityCenterAngleZ, -limitBodyRotationZ, limitBodyRotationZ);
playerGravityCenter.localEulerAngles = new Vector3 (gravityCenterAngleX, currentExtraBodyRotation, gravityCenterAngleZ);
float forwardSpeed = (mainRigidbody.transform.InverseTransformDirection (mainRigidbody.linearVelocity).z) * 3f;
float bodyRotation = extraBodyRotation;
float spineRotation = extraSpineRotation;
if (forwardSpeed < -2) {
bodyRotation = -extraBodyRotation;
spineRotation = -extraSpineRotation;
}
currentExtraBodyRotation = Mathf.Lerp (currentExtraBodyRotation, bodyRotation, Time.deltaTime * 5);
currentExtraSpineRotation = Mathf.Lerp (currentExtraSpineRotation, spineRotation, Time.deltaTime * 5);
}
}
}
void LateUpdate ()
{
if (driving && !firstPersonActive && animationActive) {
if (addExtraMovementToBody) {
Quaternion rotationX = Quaternion.FromToRotation (bodyLookPivot.InverseTransformDirection (hoverBoardTransform.right),
bodyLookPivot.InverseTransformDirection (hoverBoardTransform.forward));
Vector3 directionX = rotationX.eulerAngles;
Quaternion rotationZ = Quaternion.FromToRotation (bodyLookPivot.InverseTransformDirection (hoverBoardTransform.forward),
bodyLookPivot.InverseTransformDirection (hoverBoardTransform.forward));
Vector3 directionZ = rotationZ.eulerAngles;
float angleX = directionX.x;
if (angleX > 180) {
angleX = Mathf.Clamp (angleX, maxSpineRotationX, 360);
} else {
angleX = Mathf.Clamp (angleX, 0, minSpineRotationX);
}
bodyLookPivot.localEulerAngles = new Vector3 (angleX - angleZ, bodyLookPivot.localEulerAngles.y, directionZ.z - currentExtraSpineRotation);
}
if (addMovementToArms) {
float armRotation = angleZ;
armRotation = Mathf.Clamp (armRotation, -maxArmsRotation, maxArmsRotation);
float rightArmRotationX = rightArm.localEulerAngles.x - armRotation;
rightArm.localEulerAngles = new Vector3 (rightArmRotationX, rightArm.localEulerAngles.y, rightArm.localEulerAngles.z);
float leftArmRotationX = leftArm.localEulerAngles.x + armRotation;
leftArm.localEulerAngles = new Vector3 (leftArmRotationX, leftArm.localEulerAngles.y, leftArm.localEulerAngles.z);
}
if (addMovementToHead) {
float headAngle = 0;
if (mainHoverBoardController.motorInput < 0 &&
(Mathf.Abs (mainHoverBoardController.currentSpeed) > minBackwardVelocityToHeadRotation || mainHoverBoardController.motorInput < -0.8f)) {
headAngle = maxHeadRotationBackward;
}
headLookCenterCurrentRotation = Mathf.Lerp (headLookCenterCurrentRotation, headAngle, Time.deltaTime * headRotationSpeed);
headLookCenter.localEulerAngles = new Vector3 (0, headLookCenterCurrentRotation, 0);
}
}
}
//the player is getting on or off from the vehicle, so
public void changeVehicleState (bool state)
{
driving = state;
animationActive = state;
//set the audio values if the player is getting on or off from the vehicle
if (driving) {
//set the same state in the gravity control components
animator = hoverBoardTransform.GetComponentInChildren<Animator> ();
mainUpperBodyRotationSystem = hoverBoardTransform.GetComponentInChildren<upperBodyRotationSystem> ();
if (addMovementToBody) {
if (mainUpperBodyRotationSystem != null) {
mainUpperBodyRotationSystem.enableOrDisableIKUpperBody (true);
mainUpperBodyRotationSystem.setTemporalObjectToFollow (bodyLookCenter);
}
}
bodyLookPivot.localEulerAngles = Vector3.zero;
if (animator != null) {
rightArm = animator.GetBoneTransform (HumanBodyBones.RightUpperArm);
leftArm = animator.GetBoneTransform (HumanBodyBones.LeftUpperArm);
}
} else {
if (addMovementToBody) {
if (mainUpperBodyRotationSystem != null) {
mainUpperBodyRotationSystem.enableOrDisableIKUpperBody (false);
mainUpperBodyRotationSystem.setTemporalObjectToFollow (null);
}
}
}
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 65ed2615d0f1672408d178125cda0868
timeCreated: 1613579173
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/Vehicle Controllers/hoverBoardAnimationSystem.cs
uploadId: 814740

View File

@@ -0,0 +1,715 @@
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using GameKitController.Audio;
public class hoverBoardController : vehicleController
{
[Header ("Custom Settings")]
[Space]
public List<hoverEngineSettings> hoverEngineList = new List<hoverEngineSettings> ();
public OtherCarParts otherCarParts;
public hoverCraftSettings settings;
public float stabilityForce = 1;
public float stabilitySpeed = 2;
public float minSteerInputIdle = 0.4f;
public float minSteerInputMoving = 0.4f;
float currentMinSteerInput;
public hoverBoardAnimationSystem mainHoverBoardAnimationSystem;
[HideInInspector] public bool firstPersonActive;
float audioPower = 0;
float maxEnginePower;
float resetTimer;
float originalJumpPower;
int i;
int collisionForceLimit = 5;
bool anyOnGround;
bool rotating;
Vector3 gravityForce;
hoverEngineSettings currentEngine;
int hoverEngineListCount;
ParticleSystem currentParticleSystem;
Vector3 transformForward;
Vector3 transformUp;
protected override void InitializeAudioElements ()
{
otherCarParts.InitializeAudioElements ();
}
public override void Awake ()
{
base.Awake ();
}
public override void Start ()
{
base.Start ();
//get the boost particles inside the vehicle
hoverEngineListCount = hoverEngineList.Count;
for (i = 0; i < otherCarParts.boostingParticles.Count; i++) {
if (otherCarParts.boostingParticles [i].gameObject.activeSelf) {
otherCarParts.boostingParticles [i].gameObject.SetActive (false);
}
}
for (i = 0; i < hoverEngineList.Count; i++) {
currentEngine = hoverEngineList [i];
currentEngine.hasTurbine = currentEngine.turbine != null;
currentEngine.hasParticles = currentEngine.ParticleSystem != null;
}
setAudioState (otherCarParts.engineAudioElement, 5, 0, true, false, false);
otherCarParts.gravityCenterCollider.enabled = false;
originalJumpPower = vehicleControllerSettings.jumpPower;
}
public override void vehicleUpdate ()
{
base.vehicleUpdate ();
mainRigidbody.centerOfMass = settings.centerOfMassOffset;
maxEnginePower = 0;
for (i = 0; i < hoverEngineListCount; i++) {
currentEngine = hoverEngineList [i];
if (currentEngine.maxEnginePower > maxEnginePower) {
maxEnginePower = currentEngine.maxEnginePower;
}
//configure every particle system according to the engine state
float rpm = Mathf.Lerp (currentEngine.minRPM, currentEngine.maxRPM, currentEngine.maxEnginePower);
if (currentEngine.hasTurbine) {
currentEngine.turbine.Rotate (0, rpm * Time.deltaTime * 6, 0);
}
if (currentEngine.hasParticles) {
var hoverEngineParticleEmission = currentEngine.ParticleSystem.emission;
hoverEngineParticleEmission.rateOverTime = currentEngine.maxEmission * currentEngine.maxEnginePower;
currentEngine.ParticleSystem.transform.position = currentEngine.hit.point + currentEngine.dustHeight * currentEngine.hit.normal;
currentEngine.ParticleSystem.transform.LookAt (currentEngine.hit.point + 10 * currentEngine.hit.normal);
}
}
audioPower = Mathf.Lerp (maxEnginePower, motorInput, settings.audioEngineSpeed);
otherCarParts.engineAudio.volume = Mathf.Lerp (settings.engineMinVolume, settings.engineMaxVolume, audioPower);
otherCarParts.engineAudio.pitch = Mathf.Lerp (settings.minAudioPitch, settings.maxAudioPitch, audioPower);
//reset the vehicle rotation if it is upside down
if (currentSpeed < 5) {
//check the current rotation of the vehicle with respect to the normal of the gravity normal component, which always point the up direction
float angle = Vector3.Angle (currentNormal, transform.up);
if (angle > 60 && !rotating) {
resetTimer += Time.deltaTime;
if (resetTimer > settings.timeToFlip) {
resetTimer = 0;
StartCoroutine (rotateVehicle ());
}
} else {
resetTimer = 0;
}
}
}
void FixedUpdate ()
{
currentSpeed = mainRigidbody.linearVelocity.magnitude;
//apply turn
if (usingHoverBoardWaypoint) {
return;
}
if (Mathf.Approximately (horizontalAxis, 0)) {
float localR = Vector3.Dot (mainRigidbody.angularVelocity, transform.up);
mainRigidbody.AddRelativeTorque (0, -localR * settings.brakingTorque, 0);
} else {
float targetRoll = -settings.rollOnTurns * horizontalAxis;
float roll = Mathf.Asin (transform.right.y) * Mathf.Rad2Deg;
// only apply additional roll if we're not "overrolled"
if (Mathf.Abs (roll) > Mathf.Abs (targetRoll)) {
roll = 0;
} else {
roll = Mathf.DeltaAngle (roll, targetRoll);
}
mainRigidbody.AddRelativeTorque (0, horizontalAxis * settings.steeringTorque, roll * settings.rollOnTurnsTorque);
}
if (!usingGravityControl && !jumpInputPressed) {
Vector3 localVelocity = transform.InverseTransformDirection (mainRigidbody.linearVelocity);
Vector3 extraForce = Vector3.Scale (settings.extraRigidbodyForce, localVelocity);
mainRigidbody.AddRelativeForce (mainRigidbody.mass * (-extraForce));
//use every engine to keep the vehicle in the air
for (i = 0; i < hoverEngineListCount; i++) {
currentEngine = hoverEngineList [i];
if (!currentEngine.mainEngine) {
//find force direction by rotating local up vector towards world up
Vector3 engineUp = currentEngine.engineTransform.up;
Vector3 enginePosition = currentEngine.engineTransform.position;
gravityForce = (9.8f * currentNormal).normalized;
engineUp = Vector3.RotateTowards (engineUp, gravityForce, currentEngine.maxEngineAngle * Mathf.Deg2Rad, 1);
//check if the vehicle is on ground
currentEngine.maxEnginePower = 0;
if (Physics.Raycast (enginePosition, -engineUp, out currentEngine.hit, currentEngine.maxHeight, settings.layer)) {
//calculate down force
currentEngine.maxEnginePower = Mathf.Pow ((currentEngine.maxHeight - currentEngine.hit.distance) / currentEngine.maxHeight, currentEngine.Exponent);
float force = currentEngine.maxEnginePower * currentEngine.engineForce;
float velocityUp = Vector3.Dot (mainRigidbody.GetPointVelocity (enginePosition), engineUp);
float drag = -velocityUp * Mathf.Abs (velocityUp) * currentEngine.damping;
mainRigidbody.AddForceAtPosition ((force + drag) * engineUp, enginePosition);
}
}
}
Vector3 torqueVector = Vector3.Cross (transform.up, mainVehicleCameraController.transform.up);
mainRigidbody.AddTorque ((stabilityForce * stabilitySpeed) * torqueVector);
//if the handbrake is pressed, set the brake torque value in every wheel
bool brakeActive = (braking || isBrakeActive ());
if (brakeActive) {
for (i = 0; i < hoverEngineListCount; i++) {
currentEngine = hoverEngineList [i];
if (currentEngine.mainEngine) {
mainRigidbody.linearVelocity = Vector3.Lerp (mainRigidbody.linearVelocity, Vector3.zero, Time.deltaTime);
}
}
} else {
transformForward = transform.forward;
transformUp = transform.up;
for (i = 0; i < hoverEngineListCount; i++) {
currentEngine = hoverEngineList [i];
if (currentEngine.mainEngine) {
float movementMultiplier = settings.inAirMovementMultiplier;
if (Physics.Raycast (currentEngine.engineTransform.position, -transformUp, out currentEngine.hit, currentEngine.maxHeight, settings.layer)) {
movementMultiplier = 1;
}
gravityForce = (9.8f * currentNormal).normalized;
//current speed along forward axis
float speed = Vector3.Dot (mainRigidbody.linearVelocity, transformForward);
//if the vehicle doesn't move by input, apply automatic brake
bool isAutoBraking = Mathf.Approximately (motorInput, 0) && settings.autoBrakingDeceleration > 0;
float thrust = motorInput;
if (isAutoBraking) {
thrust = -Mathf.Sign (speed) * settings.autoBrakingDeceleration / settings.maxBrakingDeceleration;
}
//check if it is braking, for example speed and thrust have opposing signs
bool isBraking = speed * motorInput < 0;
//don't apply force if speed is max already
if (Mathf.Abs (speed) < settings.maxSpeed || isBraking) {
//position on speed curve
float normSpeed = Mathf.Sign (motorInput) * speed / settings.maxSpeed;
//apply acceleration curve and select proper maximum value
float acc = settings.accelerationCurve.Evaluate (normSpeed) * (isBraking ? settings.maxBrakingDeceleration : thrust > 0 ? settings.maxForwardAcceleration : settings.maxReverseAcceleration);
//drag should be added to the acceleration
float sdd = speed * settings.extraRigidbodyForce.z;
float dragForce = sdd + mainRigidbody.linearDamping * speed;
float force = acc * thrust + dragForce;
//reduce acceleration if the vehicle is close to vertical orientation and is trrying to go higher
float y = Vector3.Dot (transformForward, gravityForce);
if (settings.maxSurfaceAngle < 90 && y * thrust > 0) {
if (!isAutoBraking) {
float pitch2 = Mathf.Asin (Mathf.Abs (y)) * Mathf.Rad2Deg;
if (pitch2 > settings.maxSurfaceAngle) {
float forceDecrease = (pitch2 - settings.maxSurfaceAngle) / (90 - settings.maxSurfaceAngle) * settings.maxSurfaceVerticalReduction;
force /= 1 + forceDecrease;
}
}
}
mainRigidbody.AddForce ((force * boostInput * movementMultiplier) * transformForward, ForceMode.Acceleration);
}
}
}
}
}
anyOnGround = true;
int totalWheelsOnAir = 0;
for (i = 0; i < hoverEngineListCount; i++) {
currentEngine = hoverEngineList [i];
if (!Physics.Raycast (currentEngine.engineTransform.position, -currentEngine.engineTransform.up, out currentEngine.hit, currentEngine.maxHeight, settings.layer)) {
totalWheelsOnAir++;
}
}
//if the total amount of wheels in the air is equal to the number of wheel sin the vehicle, anyOnGround is false
if (totalWheelsOnAir == hoverEngineListCount && anyOnGround) {
anyOnGround = false;
}
}
IEnumerator jumpCoroutine ()
{
jumpInputPressed = true;
yield return new WaitForSeconds (0.5f);
jumpInputPressed = false;
}
public override void enterOrExitFromWayPoint (bool state)
{
usingHoverBoardWaypoint = state;
mainVehicleGravityControl.enabled = !state;
mainRigidbody.isKinematic = state;
if (usingHoverBoardWaypoint) {
lastTimeReleasedFromWaypoint = 0;
} else {
lastTimeReleasedFromWaypoint = Time.time;
}
}
public override float getLastTimeReleasedFromWaypoint ()
{
return lastTimeReleasedFromWaypoint;
}
public override bool isUsingHoverBoardWaypoint ()
{
return usingHoverBoardWaypoint;
}
public override void receiveWayPoints (hoverBoardWayPoints wayPoints)
{
wayPointsManager = wayPoints;
}
public override void updateCameraSteerState ()
{
if (localLook.z < 0f) {
localLook.x = Mathf.Sign (localLook.x);
}
steering = localLook.x;
steering = Mathf.Clamp (steering, -1f, 1f);
if (axisValues.y != 0) {
currentMinSteerInput = minSteerInputMoving;
} else {
currentMinSteerInput = minSteerInputIdle;
}
if (Mathf.Abs (steering) > currentMinSteerInput) {
horizontalAxis = steering;
} else {
horizontalAxis = 0;
}
}
//if the vehicle is using the gravity control, set the state in this component
public override void changeGravityControlUse (bool state)
{
base.changeGravityControlUse (state);
}
//the player is getting on or off from the vehicle, so
public override void changeVehicleState ()
{
base.changeVehicleState ();
otherCarParts.gravityCenterCollider.enabled = driving;
mainHoverBoardAnimationSystem.changeVehicleState (driving);
}
public override void setTurnOnState ()
{
setAudioState (otherCarParts.engineAudioElement, 5, 0, true, true, false);
}
public override void setTurnOffState (bool previouslyTurnedOn)
{
base.setTurnOffState (previouslyTurnedOn);
if (previouslyTurnedOn) {
setAudioState (otherCarParts.engineAudioElement, 5, 0, false, false, true);
}
}
public override void turnOnOrOff (bool state, bool previouslyTurnedOn)
{
base.turnOnOrOff (state, previouslyTurnedOn);
}
public override bool isDrivingActive ()
{
return driving;
}
public override void setEngineOnOrOffState ()
{
base.setEngineOnOrOffState ();
}
//the vehicle has been destroyed, so disabled every component in it
public override void disableVehicle ()
{
//stop the audio sources
setAudioState (otherCarParts.engineAudioElement, 5, 0, false, false, false);
setTurnOffState (false);
otherCarParts.gravityCenterCollider.enabled = false;
//disable the controller
this.enabled = false;
mainHoverBoardAnimationSystem.changeVehicleState (false);
}
//reset the vehicle rotation if it is upside down
IEnumerator rotateVehicle ()
{
rotating = true;
Quaternion currentRotation = transform.rotation;
//rotate in the forward direction of the vehicle
Quaternion dstRotPlayer = Quaternion.LookRotation (transform.forward, currentNormal);
for (float t = 0; t < 1;) {
t += Time.deltaTime * 3;
transform.rotation = Quaternion.Slerp (currentRotation, dstRotPlayer, t);
mainRigidbody.linearVelocity = Vector3.zero;
yield return null;
}
rotating = false;
}
//if the vehicle is using the boost, set the boost particles
public override void usingBoosting ()
{
base.usingBoosting ();
for (int i = 0; i < otherCarParts.boostingParticles.Count; i++) {
currentParticleSystem = otherCarParts.boostingParticles [i];
if (usingBoost) {
if (!currentParticleSystem.isPlaying) {
if (!currentParticleSystem.gameObject.activeSelf) {
currentParticleSystem.gameObject.SetActive (true);
}
currentParticleSystem.Play ();
var boostingParticlesMain = currentParticleSystem.main;
boostingParticlesMain.loop = true;
}
} else {
if (currentParticleSystem.isPlaying) {
var boostingParticlesMain = currentParticleSystem.main;
boostingParticlesMain.loop = false;
}
}
}
}
//use a jump platform
public void useVehicleJumpPlatform (Vector3 direction)
{
StartCoroutine (jumpCoroutine ());
mainRigidbody.AddForce (mainRigidbody.mass * direction, ForceMode.Impulse);
}
public void useJumpPlatformParable (Vector3 direction)
{
Vector3 jumpForce = direction;
mainRigidbody.AddForce (jumpForce, ForceMode.VelocityChange);
}
public void setNewJumpPower (float newJumpPower)
{
vehicleControllerSettings.jumpPower = newJumpPower;
}
public void setOriginalJumpPower ()
{
vehicleControllerSettings.jumpPower = originalJumpPower;
}
public void setCanJumpState (bool state)
{
vehicleControllerSettings.canJump = state;
}
//OVERRIDE FUNCTIONS FOR VEHICLE CONTROLLER
//if any collider in the vehicle collides, then
public override void setCollisionDetected (Collision currentCollision)
{
//check that the collision is not with the player
if (!currentCollision.gameObject.CompareTag ("Player")) {
//if the velocity of the collision is higher that the limit
if (currentCollision.relativeVelocity.magnitude > collisionForceLimit) {
//set the collision audio with a random collision clip
if (otherCarParts.crashAudioElements.Length > 0) {
setAudioState (otherCarParts.crashAudioElements [UnityEngine.Random.Range (0, otherCarParts.crashAudioElements.Length)], 5, 1, false, true, false);
}
}
}
}
public override void startBrakeVehicleToStopCompletely ()
{
braking = true;
}
public override void endBrakeVehicleToStopCompletely ()
{
braking = false;
}
public override float getCurrentSpeed ()
{
return currentSpeed;
}
//CALL INPUT FUNCTIONS
public override void inputJump ()
{
if (driving && !usingGravityControl && isTurnedOn && vehicleControllerSettings.canJump) {
if (anyOnGround && !jumpInputPressed) {
StartCoroutine (jumpCoroutine ());
mainRigidbody.AddForce (mainRigidbody.mass * vehicleControllerSettings.jumpPower * currentNormal, ForceMode.Impulse);
}
if (usingHoverBoardWaypoint) {
StartCoroutine (jumpCoroutine ());
pickOrReleaseHoverboardVehicle (false, false);
Vector3 totalJumpForce = mainRigidbody.mass * hoverboardJumpForce * (currentNormal + transform.forward);
if (useHoverboardJumpClamp) {
totalJumpForce = Vector3.ClampMagnitude (totalJumpForce, hoverboardJumpClamp);
}
mainRigidbody.AddForce (totalJumpForce, ForceMode.Impulse);
}
}
}
public override void inputHoldOrReleaseTurbo (bool holdingButton)
{
if (driving && !usingGravityControl && isTurnedOn && !usingHoverBoardWaypoint) {
//boost input
if (holdingButton) {
if (vehicleControllerSettings.canUseBoost) {
usingBoost = true;
//set the camera move away action
mainVehicleCameraController.usingBoost (true, vehicleControllerSettings.boostCameraShakeStateName,
vehicleControllerSettings.useBoostCameraShake, vehicleControllerSettings.moveCameraAwayOnBoost);
}
} else {
//stop boost
usingBoost = false;
//disable the camera move away action
mainVehicleCameraController.usingBoost (false, vehicleControllerSettings.boostCameraShakeStateName,
vehicleControllerSettings.useBoostCameraShake, vehicleControllerSettings.moveCameraAwayOnBoost);
//disable the boost particles
usingBoosting ();
boostInput = 1;
}
}
}
public override void inputSetTurnOnState ()
{
if (driving && !usingGravityControl) {
if (mainVehicleHUDManager.canSetTurnOnState) {
setEngineOnOrOffState ();
}
}
}
public override void inputHoldOrReleaseBrake (bool holdingButton)
{
if (driving && !usingGravityControl) {
braking = holdingButton;
}
}
[System.Serializable]
public class hoverEngineSettings
{
public string Name;
public Transform engineTransform;
public ParticleSystem ParticleSystem;
public float maxEmission = 100;
public float dustHeight = 0.1f;
public float maxHeight = 2;
public float engineForce = 300;
public float damping = 10;
public float Exponent = 2;
public float maxEngineAngle = 15;
public bool mainEngine;
public float minRPM = 100;
public float maxRPM = 200;
public Transform turbine;
[HideInInspector] public RaycastHit hit;
[HideInInspector] public float maxEnginePower;
[HideInInspector] public bool hasTurbine;
[HideInInspector] public bool hasParticles;
}
[System.Serializable]
public class OtherCarParts
{
public Transform COM;
public GameObject chassis;
public AudioClip engineClip;
public AudioElement engineAudioElement;
public AudioClip[] crashClips;
public AudioElement[] crashAudioElements;
public AudioSource engineAudio;
public AudioSource crashAudio;
public List<ParticleSystem> boostingParticles = new List<ParticleSystem> ();
public Collider gravityCenterCollider;
public void InitializeAudioElements ()
{
if (engineClip != null) {
engineAudioElement.clip = engineClip;
}
if (crashClips != null && crashClips.Length > 0) {
crashAudioElements = new AudioElement[crashClips.Length];
for (var i = 0; i < crashClips.Length; i++) {
crashAudioElements [i] = new AudioElement { clip = crashClips [i] };
}
}
if (engineAudio != null) {
engineAudioElement.audioSource = engineAudio;
}
if (crashAudio != null) {
foreach (var audioElement in crashAudioElements) {
audioElement.audioSource = crashAudio;
}
}
}
}
[System.Serializable]
public class hoverCraftSettings
{
public LayerMask layer;
public float steeringTorque = 120;
public float brakingTorque = 200;
public float maxSpeed = 30;
public float maxForwardAcceleration = 20;
public float maxReverseAcceleration = 15;
public float maxBrakingDeceleration = 30;
public float autoBrakingDeceleration = 20;
public float rollOnTurns = 10;
public float rollOnTurnsTorque = 10;
public float timeToFlip = 2;
public float audioEngineSpeed = 0.5f;
public float engineMinVolume = 0.5f;
public float engineMaxVolume = 1;
public float minAudioPitch = 0.4f;
public float maxAudioPitch = 1;
public AnimationCurve accelerationCurve;
public float maxSurfaceVerticalReduction = 10;
public float maxSurfaceAngle = 110;
public Vector3 extraRigidbodyForce = new Vector3 (2, 0.1f, 0.2f);
public Vector3 centerOfMassOffset;
[Range (0, 1)] public float inAirMovementMultiplier;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: e3ea73ff3e032e84782cb52826cc8b0c
timeCreated: 1468588219
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/Vehicle Controllers/hoverBoardController.cs
uploadId: 814740

View File

@@ -0,0 +1,830 @@
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using GameKitController.Audio;
public class hoverCraftController : vehicleController
{
[Header ("Custom Settings")]
[Space]
public float maxSteeringTorque = 1400;
public float rollOnTurns = 10;
public float rollOnTurnsTorque = 20;
public float steerBrakingTorque = 1400;
public float brakingTorque;
public float pitchCompensationTorque;
public float rollCompensationTorque = 10;
public float timeToFlip = 2;
public float audioEngineSpeed;
public float engineMinVolume = 0.5f;
public float engineMaxVolume = 1;
public float minAudioPitch = 0.5f;
public float maxAudioPitch = 1.2f;
public float maxForwardAcceleration = 20;
public float maxReverseAcceleration = 15;
public float maxBrakingDeceleration = 30;
public float autoBrakingDeceleration;
public float maxSpeed = 30;
public AnimationCurve accelerationCurve;
public float verticalReduction = 10;
public float maxPitchAngle = 45;
public Vector3 extraRigidbodyForce;
public float minSteerInputIdle = 0.4f;
public float minSteerInputMoving = 0.4f;
[Space]
[Header ("Hovercraft Settings")]
[Space]
public List<hoverEngineSettings> hoverEngineList = new List<hoverEngineSettings> ();
public OtherCarParts otherCarParts;
public hoverCraftSettings settings;
[Space]
[Header ("Debug")]
[Space]
public bool anyOnGround;
float audioPower = 0;
float maxEnginePower;
float resetTimer;
float steerInput;
float forwardInput;
float originalJumpPower;
int i;
int collisionForceLimit = 5;
bool rotating;
float leftInput = 0;
float rightInput = 0;
float currentMinSteerInput;
hoverEngineSettings currentEngine;
int hoverEngineListCount;
ParticleSystem currentParticleSystem;
protected override void InitializeAudioElements ()
{
otherCarParts.InitializeAudioElements ();
}
public override void Awake ()
{
base.Awake ();
}
public override void Start ()
{
base.Start ();
hoverEngineListCount = hoverEngineList.Count;
//get the boost particles inside the vehicle
for (i = 0; i < otherCarParts.boostingParticles.Count; i++) {
if (otherCarParts.boostingParticles [i].gameObject.activeSelf) {
otherCarParts.boostingParticles [i].gameObject.SetActive (false);
}
}
for (i = 0; i < hoverEngineList.Count; i++) {
currentEngine = hoverEngineList [i];
currentEngine.hasTurbine = currentEngine.turbine != null;
currentEngine.hasParticles = currentEngine.ParticleSystem != null;
}
setAudioState (otherCarParts.engineAudioElement, 5, 0, true, false, false);
setAudioState (otherCarParts.engineStartAudioElement, 5, 0.7f, false, false, false);
originalJumpPower = vehicleControllerSettings.jumpPower;
}
public override void vehicleUpdate ()
{
base.vehicleUpdate ();
maxEnginePower = 0;
for (i = 0; i < hoverEngineListCount; i++) {
currentEngine = hoverEngineList [i];
if (currentEngine.maxEnginePower > maxEnginePower) {
maxEnginePower = currentEngine.maxEnginePower;
}
//configure every particle system according to the engine state
float rpm = Mathf.Lerp (currentEngine.minRPM, currentEngine.maxRPM, currentEngine.maxEnginePower);
if (currentEngine.hasTurbine) {
currentEngine.turbine.transform.Rotate (0, rpm * Time.deltaTime * 6, 0);
}
if (currentEngine.hasParticles) {
var hoverEngineParticleEmission = currentEngine.ParticleSystem.emission;
hoverEngineParticleEmission.rateOverTime = currentEngine.maxEmission * currentEngine.maxEnginePower;
currentEngine.ParticleSystem.transform.position =
currentEngine.hit.point + currentEngine.dustHeight * currentEngine.hit.normal;
currentEngine.ParticleSystem.transform.LookAt (currentEngine.hit.point + 10 * currentEngine.hit.normal);
}
}
audioPower = Mathf.Lerp (maxEnginePower, motorInput, audioEngineSpeed);
otherCarParts.engineAudio.volume = Mathf.Lerp (engineMinVolume, engineMaxVolume, audioPower);
otherCarParts.engineAudio.pitch = Mathf.Lerp (minAudioPitch, maxAudioPitch, audioPower);
if (Mathf.Abs (horizontalAxis) > 0.05f) {
steerInput = Mathf.Lerp (steerInput, horizontalAxis, Time.deltaTime * 10);
} else {
steerInput = Mathf.Lerp (steerInput, horizontalAxis, Time.deltaTime * 10);
}
if (Mathf.Abs (motorInput) > 0.05f) {
forwardInput = Mathf.Lerp (forwardInput, motorInput, Time.deltaTime * 10);
} else {
forwardInput = Mathf.Lerp (forwardInput, motorInput, Time.deltaTime * 10);
}
float left = 0;
float right = 0;
if ((forwardInput > 0.05f || forwardInput < -0.05f) && (steerInput < 0.05f && steerInput > -0.05f)) {
left = right = forwardInput;
//print("moving forward or backward");
} else if (forwardInput > 0.05f && steerInput > 0) {
left = forwardInput;
right = -steerInput;
//print("moving forward and to the right");
} else if (forwardInput > 0.05f && steerInput < 0) {
left = steerInput;
right = forwardInput;
//print("moving forward and to the left");
} else if ((forwardInput < 0.05f && forwardInput > -0.05f) && steerInput > 0) {
left = 0;
right = steerInput;
//print("moving to the right");
} else if ((forwardInput < 0.05f && forwardInput > -0.05f) && steerInput < 0) {
left = -steerInput;
right = 0;
//print("moving to the left");
} else if (forwardInput < -0.05f && steerInput > 0) {
left = 0;
right = -steerInput;
//print("moving backward and to the right");
} else if (forwardInput < -0.05f && steerInput < 0) {
left = steerInput;
right = 0;
//print("moving backward and to the left");
}
leftInput = Mathf.Lerp (leftInput, left, Time.deltaTime * 10);
rightInput = Mathf.Lerp (rightInput, right, Time.deltaTime * 10);
Vector3 rightHandLebarEuler = otherCarParts.rightHandLebar.transform.localEulerAngles;
Vector3 lefttHandLebarEuler = otherCarParts.leftHandLebar.transform.localEulerAngles;
otherCarParts.rightHandLebar.transform.localRotation = Quaternion.Euler (settings.steerAngleLimit * rightInput * 2, rightHandLebarEuler.y, rightHandLebarEuler.z);
otherCarParts.leftHandLebar.transform.localRotation = Quaternion.Euler (settings.steerAngleLimit * leftInput * 2, lefttHandLebarEuler.y, lefttHandLebarEuler.z);
//reset the vehicle rotation if it is upside down
if (currentSpeed < 5) {
//check the current rotation of the vehicle with respect to the normal of the gravity normal component, which always point the up direction
float angle = Vector3.Angle (currentNormal, transform.up);
if (angle > 60 && !rotating) {
resetTimer += Time.deltaTime;
if (resetTimer > timeToFlip) {
resetTimer = 0;
StartCoroutine (rotateVehicle ());
}
}
}
}
void FixedUpdate ()
{
currentSpeed = mainRigidbody.linearVelocity.magnitude;
if (usingHoverBoardWaypoint) {
return;
}
//apply turn
if (Mathf.Approximately (horizontalAxis, 0)) {
float localR = Vector3.Dot (mainRigidbody.angularVelocity, transform.up);
mainRigidbody.AddRelativeTorque (0, -localR * steerBrakingTorque, 0);
} else {
float targetRoll = -rollOnTurns * horizontalAxis;
float roll = Mathf.Asin (transform.right.y) * Mathf.Rad2Deg;
if (Mathf.Abs (roll) > Mathf.Abs (targetRoll)) {
roll = 0;
} else {
roll = Mathf.DeltaAngle (roll, targetRoll);
}
mainRigidbody.AddRelativeTorque (0, horizontalAxis * maxSteeringTorque, roll * rollOnTurnsTorque);
}
if (!usingGravityControl && !jumpInputPressed) {
Vector3 localVelocity = transform.InverseTransformDirection (mainRigidbody.linearVelocity);
Vector3 extraForce = Vector3.Scale (localVelocity, extraRigidbodyForce);
mainRigidbody.AddRelativeForce (mainRigidbody.mass * (-extraForce));
Vector3 gravityForce = (9.8f * currentNormal).normalized;
//use every engine to keep the vehicle in the air
for (i = 0; i < hoverEngineListCount; i++) {
currentEngine = hoverEngineList [i];
//if the current engine is the main engine
if (!currentEngine.mainEngine) {
//find force direction by rotating local up vector towards world up
Vector3 engineUp = currentEngine.engineTransform.up;
Vector3 enginePosition = currentEngine.engineTransform.position;
engineUp = Vector3.RotateTowards (engineUp, gravityForce, currentEngine.maxEngineAngle * Mathf.Deg2Rad, 1);
//check if the vehicle is on ground
currentEngine.maxEnginePower = 0;
if (Physics.Raycast (enginePosition, -engineUp, out currentEngine.hit, currentEngine.maxHeight, settings.layer)) {
//calculate down force
currentEngine.maxEnginePower = Mathf.Pow ((currentEngine.maxHeight - currentEngine.hit.distance) / currentEngine.maxHeight, currentEngine.Exponent);
float force = currentEngine.maxEnginePower * currentEngine.engineForce;
float velocityUp = Vector3.Dot (mainRigidbody.GetPointVelocity (enginePosition), engineUp);
float drag = -velocityUp * Mathf.Abs (velocityUp) * currentEngine.damping;
mainRigidbody.AddForceAtPosition ((force + drag) * engineUp, enginePosition);
}
} else {
//find current local pitch and roll
float pitch = Mathf.Asin (Vector3.Dot (transform.forward, gravityForce)) * Mathf.Rad2Deg;
float roll = Mathf.Asin (Vector3.Dot (transform.right, gravityForce)) * Mathf.Rad2Deg;
pitch = Mathf.DeltaAngle (pitch, 0);
roll = Mathf.DeltaAngle (roll, 0);
//apply compensation torque
float auxPitch = -pitch * pitchCompensationTorque;
float auxRoll = roll * rollCompensationTorque;
if (!anyOnGround) {
auxPitch *= 0.5f;
auxRoll *= 0.5f;
}
mainRigidbody.AddRelativeTorque (pitch, 0, auxRoll);
}
}
bool brakeActive = (braking || isBrakeActive ());
if (brakeActive) {
float localR = Vector3.Dot (mainRigidbody.angularVelocity, transform.up);
mainRigidbody.AddRelativeTorque (0, -localR * brakingTorque, 0);
for (i = 0; i < hoverEngineListCount; i++) {
currentEngine = hoverEngineList [i];
if (currentEngine.mainEngine) {
mainRigidbody.linearVelocity = Vector3.Lerp (mainRigidbody.linearVelocity, Vector3.zero, Time.deltaTime);
}
}
} else {
for (i = 0; i < hoverEngineListCount; i++) {
currentEngine = hoverEngineList [i];
if (currentEngine.mainEngine) {
float movementMultiplier = settings.inAirMovementMultiplier;
if (Physics.Raycast (currentEngine.engineTransform.position, -transform.up, out currentEngine.hit, currentEngine.maxHeight, settings.layer)) {
movementMultiplier = 1;
}
//current speed along forward axis
float speed = Vector3.Dot (mainRigidbody.linearVelocity, transform.forward);
//if the vehicle doesn't move by input, apply automatic brake
bool isAutoBraking = Mathf.Approximately (motorInput, 0) && autoBrakingDeceleration > 0;
float thrust = motorInput;
if (isAutoBraking) {
thrust = -Mathf.Sign (speed) * autoBrakingDeceleration / maxBrakingDeceleration;
}
//check if it is braking, for example speed and thrust have opposing signs
bool isBraking = speed * motorInput < 0;
//don't apply force if speed is max already
if (Mathf.Abs (speed) < maxSpeed || isBraking) {
//position on speed curve
float normSpeed = Mathf.Sign (motorInput) * speed / maxSpeed;
//apply acceleration curve and select proper maximum value
float acc = accelerationCurve.Evaluate (normSpeed) * (isBraking ? maxBrakingDeceleration : thrust > 0 ? maxForwardAcceleration : maxReverseAcceleration);
//drag should be added to the acceleration
float sdd = speed * extraRigidbodyForce.z;
float dragForce = sdd + mainRigidbody.linearDamping * speed;
float force = acc * thrust + dragForce;
//reduce acceleration if the vehicle is close to vertical orientation and is trrying to go higher
float y = Vector3.Dot (transform.forward, gravityForce);
if (maxPitchAngle < 90 && y * thrust > 0) {
if (!isAutoBraking) {
float pitch2 = Mathf.Asin (Mathf.Abs (y)) * Mathf.Rad2Deg;
if (pitch2 > maxPitchAngle) {
float reduction = (pitch2 - maxPitchAngle) / (90 - maxPitchAngle) * verticalReduction;
force /= 1 + reduction;
}
}
}
mainRigidbody.AddForce ((boostInput * movementMultiplier * force) * transform.forward, ForceMode.Acceleration);
}
}
}
}
}
//set the exhaust particles state
for (i = 0; i < otherCarParts.normalExhaust.Count; i++) {
if (isTurnedOn && currentSpeed < 20) {
if (!otherCarParts.normalExhaust [i].isPlaying) {
otherCarParts.normalExhaust [i].Play ();
}
} else {
if (otherCarParts.normalExhaust [i].isPlaying) {
otherCarParts.normalExhaust [i].Stop ();
}
}
}
for (i = 0; i < otherCarParts.heavyExhaust.Count; i++) {
if (isTurnedOn && currentSpeed > 10 && motorInput > 0.1f) {
if (!otherCarParts.heavyExhaust [i].isPlaying) {
otherCarParts.heavyExhaust [i].Play ();
}
} else {
if (otherCarParts.heavyExhaust [i].isPlaying) {
otherCarParts.heavyExhaust [i].Stop ();
}
}
}
anyOnGround = true;
int totalWheelsOnAir = 0;
for (i = 0; i < hoverEngineListCount; i++) {
currentEngine = hoverEngineList [i];
if (!Physics.Raycast (currentEngine.engineTransform.position, -currentEngine.engineTransform.up, out currentEngine.hit,
currentEngine.maxHeight, settings.layer)) {
totalWheelsOnAir++;
}
}
//if the total amount of wheels in the air is equal to the number of wheel sin the vehicle, anyOnGround is false
if (totalWheelsOnAir == hoverEngineListCount && anyOnGround) {
anyOnGround = false;
}
}
IEnumerator jumpCoroutine ()
{
jumpInputPressed = true;
yield return new WaitForSeconds (0.5f);
jumpInputPressed = false;
}
public override void updateCameraSteerState ()
{
if (localLook.z < 0f) {
localLook.x = Mathf.Sign (localLook.x);
}
steering = localLook.x;
steering = Mathf.Clamp (steering, -1f, 1f);
if (axisValues.y != 0) {
currentMinSteerInput = minSteerInputMoving;
} else {
currentMinSteerInput = minSteerInputIdle;
}
if (Mathf.Abs (steering) > currentMinSteerInput) {
horizontalAxis = steering;
} else {
horizontalAxis = 0;
}
}
//if the vehicle is using the gravity control, set the state in this component
public override void changeGravityControlUse (bool state)
{
base.changeGravityControlUse (state);
}
//the player is getting on or off from the vehicle, so
public override void changeVehicleState ()
{
base.changeVehicleState ();
}
public override void setTurnOnState ()
{
setAudioState (otherCarParts.engineAudioElement, 5, 0, true, true, false);
setAudioState (otherCarParts.engineStartAudioElement, 5, 0.7f, false, true, false);
}
public override void setTurnOffState (bool previouslyTurnedOn)
{
base.setTurnOffState (previouslyTurnedOn);
if (previouslyTurnedOn) {
setAudioState (otherCarParts.engineAudioElement, 5, 0, false, false, true);
setAudioState (otherCarParts.engineEndAudioElement, 5, 1, false, true, false);
}
steerInput = 0;
}
public override bool isDrivingActive ()
{
return driving;
}
public override void setEngineOnOrOffState ()
{
base.setEngineOnOrOffState ();
}
public override void turnOnOrOff (bool state, bool previouslyTurnedOn)
{
base.turnOnOrOff (state, previouslyTurnedOn);
}
//the vehicle has been destroyed, so disabled every component in it
public override void disableVehicle ()
{
//stop the audio sources
setAudioState (otherCarParts.engineAudioElement, 5, 0, false, false, false);
setAudioState (otherCarParts.engineStartAudioElement, 5, 0.7f, false, false, false);
setTurnOffState (false);
//disable the exhausts particles
for (i = 0; i < otherCarParts.normalExhaust.Count; i++) {
otherCarParts.normalExhaust [i].Stop ();
}
for (i = 0; i < otherCarParts.heavyExhaust.Count; i++) {
otherCarParts.heavyExhaust [i].Stop ();
}
//disable the controller
this.enabled = false;
}
//reset the vehicle rotation if it is upside down
IEnumerator rotateVehicle ()
{
rotating = true;
Quaternion currentRotation = transform.rotation;
//rotate in the forward direction of the vehicle
Quaternion dstRotPlayer = Quaternion.LookRotation (transform.forward, currentNormal);
for (float t = 0; t < 1;) {
t += Time.deltaTime * 3;
transform.rotation = Quaternion.Slerp (currentRotation, dstRotPlayer, t);
mainRigidbody.linearVelocity = Vector3.zero;
yield return null;
}
rotating = false;
}
//if the vehicle is using the boost, set the boost particles
public override void usingBoosting ()
{
base.usingBoosting ();
for (int i = 0; i < otherCarParts.boostingParticles.Count; i++) {
currentParticleSystem = otherCarParts.boostingParticles [i];
if (usingBoost) {
if (!currentParticleSystem.isPlaying) {
if (!currentParticleSystem.gameObject.activeSelf) {
currentParticleSystem.gameObject.SetActive (true);
}
currentParticleSystem.Play ();
var boostingParticlesMain = currentParticleSystem.main;
boostingParticlesMain.loop = true;
}
} else {
if (currentParticleSystem.isPlaying) {
var boostingParticlesMain = currentParticleSystem.main;
boostingParticlesMain.loop = false;
}
}
}
}
//use a jump platform
public void useVehicleJumpPlatform (Vector3 direction)
{
StartCoroutine (jumpCoroutine ());
mainRigidbody.AddForce (mainRigidbody.mass * direction, ForceMode.Impulse);
}
public void useJumpPlatformParable (Vector3 direction)
{
Vector3 jumpForce = direction;
mainRigidbody.AddForce (jumpForce, ForceMode.VelocityChange);
}
public void setNewJumpPower (float newJumpPower)
{
vehicleControllerSettings.jumpPower = newJumpPower * 100;
}
public void setOriginalJumpPower ()
{
vehicleControllerSettings.jumpPower = originalJumpPower;
}
public void setCanJumpState (bool state)
{
vehicleControllerSettings.canJump = state;
}
//OVERRIDE FUNCTIONS FOR VEHICLE CONTROLLER
//if any collider in the vehicle collides, then
public override void setCollisionDetected (Collision currentCollision)
{
//check that the collision is not with the player
if (!currentCollision.gameObject.CompareTag ("Player")) {
//if the velocity of the collision is higher that the limit
if (currentCollision.relativeVelocity.magnitude > collisionForceLimit) {
//set the collision audio with a random collision clip
if (otherCarParts.crashAudioElements.Length > 0) {
setAudioState (otherCarParts.crashAudioElements [UnityEngine.Random.Range (0, otherCarParts.crashAudioElements.Length)], 5, 1, false, true, false);
}
}
}
}
public override void startBrakeVehicleToStopCompletely ()
{
braking = true;
}
public override void endBrakeVehicleToStopCompletely ()
{
braking = false;
}
public override float getCurrentSpeed ()
{
return currentSpeed;
}
//CALL INPUT FUNCTIONS
public override void inputJump ()
{
if (driving && !usingGravityControl && isTurnedOn && vehicleControllerSettings.canJump) {
if (anyOnGround && !jumpInputPressed) {
StartCoroutine (jumpCoroutine ());
mainRigidbody.AddForce (mainRigidbody.mass * vehicleControllerSettings.jumpPower * currentNormal, ForceMode.Impulse);
}
if (usingHoverBoardWaypoint) {
StartCoroutine (jumpCoroutine ());
pickOrReleaseHoverboardVehicle (false, false);
Vector3 totalJumpForce = mainRigidbody.mass * hoverboardJumpForce * (currentNormal + transform.forward);
if (useHoverboardJumpClamp) {
totalJumpForce = Vector3.ClampMagnitude (totalJumpForce, hoverboardJumpClamp);
}
mainRigidbody.AddForce (totalJumpForce, ForceMode.Impulse);
}
}
}
public override void inputHoldOrReleaseTurbo (bool holdingButton)
{
if (driving && !usingGravityControl && isTurnedOn && !usingHoverBoardWaypoint) {
//boost input
if (holdingButton) {
usingBoost = true;
//set the camera move away action
mainVehicleCameraController.usingBoost (true, vehicleControllerSettings.boostCameraShakeStateName,
vehicleControllerSettings.useBoostCameraShake, vehicleControllerSettings.moveCameraAwayOnBoost);
} else {
//stop boost
usingBoost = false;
//disable the camera move away action
mainVehicleCameraController.usingBoost (false, vehicleControllerSettings.boostCameraShakeStateName,
vehicleControllerSettings.useBoostCameraShake, vehicleControllerSettings.moveCameraAwayOnBoost);
//disable the boost particles
usingBoosting ();
boostInput = 1;
}
}
}
public override void inputSetTurnOnState ()
{
if (driving && !usingGravityControl) {
if (mainVehicleHUDManager.canSetTurnOnState) {
setEngineOnOrOffState ();
}
}
}
public override void inputHorn ()
{
if (driving) {
setAudioState (otherCarParts.hornAudioElement, 5, 1, false, true, false);
}
}
public override void inputHoldOrReleaseBrake (bool holdingButton)
{
if (driving && !usingGravityControl) {
braking = holdingButton;
}
}
[System.Serializable]
public class hoverEngineSettings
{
public string Name;
public Transform engineTransform;
public ParticleSystem ParticleSystem;
public float maxEmission = 250;
public float dustHeight = 0.1f;
public float maxHeight = 2;
public float engineForce = 4000;
public float damping = 150;
public float Exponent = 2;
public float maxEngineAngle = 10;
public bool mainEngine;
public float minRPM = 100;
public float maxRPM = 150;
public Transform turbine;
[HideInInspector] public RaycastHit hit;
[HideInInspector] public float maxEnginePower;
[HideInInspector] public bool hasTurbine;
[HideInInspector] public bool hasParticles;
}
[System.Serializable]
public class OtherCarParts
{
public Transform rightHandLebar;
public Transform leftHandLebar;
public Transform COM;
public GameObject chassis;
public AudioClip engineStartClip;
public AudioElement engineStartAudioElement;
public AudioClip engineClip;
public AudioElement engineAudioElement;
public AudioClip engineEndClip;
public AudioElement engineEndAudioElement;
public AudioClip[] crashClips;
public AudioElement[] crashAudioElements;
public AudioClip hornClip;
public AudioElement hornAudioElement;
public List<ParticleSystem> normalExhaust = new List<ParticleSystem> ();
public List<ParticleSystem> heavyExhaust = new List<ParticleSystem> ();
public AudioSource engineStartAudio;
public AudioSource engineAudio;
public AudioSource crashAudio;
public AudioSource hornAudio;
public List<ParticleSystem> boostingParticles = new List<ParticleSystem> ();
public void InitializeAudioElements ()
{
if (engineStartClip != null) {
engineStartAudioElement.clip = engineStartClip;
}
if (engineClip != null) {
engineAudioElement.clip = engineClip;
}
if (engineEndClip != null) {
engineEndAudioElement.clip = engineEndClip;
}
if (crashClips != null && crashClips.Length > 0) {
crashAudioElements = new AudioElement[crashClips.Length];
for (var i = 0; i < crashClips.Length; i++) {
crashAudioElements [i] = new AudioElement { clip = crashClips [i] };
}
}
if (hornClip != null) {
hornAudioElement.clip = hornClip;
}
if (engineStartAudio != null) {
engineStartAudioElement.audioSource = engineStartAudio;
}
if (engineAudio != null) {
engineAudioElement.audioSource = engineAudio;
engineEndAudioElement.audioSource = engineAudio;
}
if (crashAudio != null) {
foreach (var audioElement in crashAudioElements) {
audioElement.audioSource = crashAudio;
}
}
if (hornAudio != null) {
hornAudioElement.audioSource = hornAudio;
}
}
}
[System.Serializable]
public class hoverCraftSettings
{
public LayerMask layer;
public float steerAngleLimit;
[Range (0, 1)] public float inAirMovementMultiplier;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: d3012a06fc1d64e4db106fd9b566f13d
timeCreated: 1467570608
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/Vehicle Controllers/hoverCraftController.cs
uploadId: 814740

View File

@@ -0,0 +1,17 @@
fileFormatVersion: 2
guid: 8a5ada0305af8104294c0d59da8b3de8
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/Vehicle Controllers/motorBikeController.cs
uploadId: 814740

View File

@@ -0,0 +1,981 @@
using UnityEngine;
using System.Collections;
public class sphereController : vehicleController
{
[Header ("Custom Settings")]
[Space]
public otherVehicleParts vehicleParts;
public vehicleSettings settings;
[Space]
[Header ("Physics Settings")]
[Space]
[SerializeField, Range (0f, 100f)]
float maxSpeed = 10f;
[SerializeField, Range (0f, 100f)]
float maxClimbSpeed = 4f;
[SerializeField, Range (0f, 100f)]
float maxBoostClimbSpeed = 4f;
[SerializeField, Range (0f, 100f)]
float maxSwimSpeed = 5f;
[SerializeField, Range (0f, 100f)]
float maxAcceleration = 10f;
[SerializeField, Range (0f, 100f)]
float maxAirAcceleration = 1f;
[SerializeField, Range (0f, 100f)]
float maxClimbAcceleration = 40f;
[SerializeField, Range (0f, 100f)]
float maxSwimAcceleration = 5f;
[SerializeField, Range (0, 5)]
int maxAirJumps = 0;
[SerializeField, Range (0, 90)]
float maxGroundAngle = 25f, maxStairsAngle = 50f;
[SerializeField, Range (90, 180)]
float maxClimbAngle = 140f;
[SerializeField, Range (0f, 100f)]
float maxSnapSpeed = 100f;
[SerializeField]
float probeDistance = 1f;
[SerializeField]
float submergenceOffset = 0.5f;
[SerializeField]
float submergenceRange = 1f;
[SerializeField]
float buoyancy = 1f;
[SerializeField, Range (0f, 10f)]
float waterDrag = 1f;
[SerializeField, Range (0.01f, 1f)]
float swimThreshold = 0.5f;
[SerializeField]
LayerMask probeMask = -1, stairsMask = -1, climbMask = -1, waterMask = 0;
[SerializeField]
float sphereRadius = 0.5f;
[SerializeField]
float sphereAlignSpeed = 45;
[SerializeField]
float sphereAirRotation = 0.5f;
[SerializeField]
float sphereSwimRotation = 2f;
public bool useClimbEnabled = true;
[Space]
[Header ("Debug")]
[Space]
public bool anyOnGround;
public int stepsSinceLastJump;
public int climbContactCount;
public bool desiresClimbing;
public int groundContactCount;
public int steepContactCount;
public int stepsSinceLastGrounded;
public Vector3 velocity;
public Vector3 moveInput;
[Space]
[Header ("Components")]
[Space]
public Transform sphereTransform;
float originalJumpPower;
Transform vehicleCameraTransform;
Rigidbody connectedBody;
Rigidbody previousConnectedBody;
Vector3 connectionVelocity;
Vector3 connectionWorldPosition;
Vector3 connectionLocalPosition;
Vector3 upAxis, rightAxis, forwardAxis;
bool desiredJump;
Vector3 contactNormal, steepNormal, climbNormal, lastClimbNormal;
Vector3 lastContactNormal, lastSteepNormal, lastConnectionVelocity;
float submergence;
int jumpPhase;
float minGroundDotProduct, minStairsDotProduct, minClimbDotProduct;
public override void Awake ()
{
base.Awake ();
OnValidate ();
}
public override void Start ()
{
base.Start ();
originalJumpPower = vehicleControllerSettings.jumpPower;
vehicleCameraTransform = mainVehicleCameraController.transform;
}
public override void vehicleUpdate ()
{
base.vehicleUpdate ();
if (isPlayerMovingOn3dWorld ()) {
moveInput.x = horizontalAxis;
moveInput.z = verticalAxis;
} else {
if (desiresClimbing) {
moveInput.z = verticalAxis;
moveInput.x = 0;
} else {
moveInput.x = verticalAxis;
moveInput.z = 0;
}
}
moveInput.y = 0;
moveInput = Vector3.ClampMagnitude (moveInput, 1f);
if (isCameraTypeFree ()) {
rightAxis = projectDirectionOnPlane (settings.vehicleCamera.transform.right, upAxis);
forwardAxis = projectDirectionOnPlane (settings.vehicleCamera.transform.forward, upAxis);
} else {
Transform currentLockedCameraTransform = mainVehicleCameraController.getLockedCameraTransform ();
if (currentLockedCameraTransform != null) {
if (isPlayerMovingOn3dWorld ()) {
rightAxis = projectDirectionOnPlane (currentLockedCameraTransform.right, upAxis);
forwardAxis = projectDirectionOnPlane (currentLockedCameraTransform.forward, upAxis);
} else {
rightAxis = projectDirectionOnPlane (currentLockedCameraTransform.right, upAxis);
forwardAxis = projectDirectionOnPlane (currentLockedCameraTransform.forward, upAxis);
}
} else {
rightAxis = Vector3.zero;
forwardAxis = Vector3.zero;
}
}
if (isSwimmingActive ()) {
setDesiresClimbingState (false);
}
updateSphereState ();
}
void setDesiresClimbingState (bool state)
{
desiresClimbing = state;
if (desiresClimbing) {
} else {
}
mainVehicleGravityControl.setGravityForcePausedState (desiresClimbing);
}
void FixedUpdate ()
{
anyOnGround = isOnGround ();
if (usingHoverBoardWaypoint) {
return;
}
upAxis = mainVehicleGravityControl.getCurrentNormal ();
Vector3 gravity = -upAxis * mainVehicleGravityControl.getGravityForce ();
fixedUpdateSphereState ();
if (insideWater ()) {
velocity *= 1f - waterDrag * submergence * Time.deltaTime;
}
adjustVelocity ();
if (desiredJump) {
desiredJump = false;
activeJump (gravity);
}
if (isClimbingActive ()) {
velocity -= contactNormal * (maxClimbAcceleration * 0.9f * Time.deltaTime);
} else if (insideWater ()) {
velocity += gravity * ((1f - buoyancy * submergence) * Time.deltaTime);
} else if (isOnGround () && velocity.sqrMagnitude < 0.01f) {
velocity += contactNormal * (Vector3.Dot (gravity, contactNormal) * Time.deltaTime);
} else if (desiresClimbing && isOnGround ()) {
velocity += (gravity - contactNormal * (maxClimbAcceleration * 0.9f)) * Time.deltaTime;
} else {
velocity += gravity * Time.deltaTime;
}
mainRigidbody.linearVelocity = velocity;
if (anyOnGround || isClimbingActive ()) {
bool brakeActive = (braking || isBrakeActive ());
if (brakeActive) {
float verticalVelocity = vehicleCameraTransform.InverseTransformDirection (mainRigidbody.linearVelocity).y;
Vector3 downVelocity = vehicleCameraTransform.up * verticalVelocity;
mainRigidbody.linearVelocity = Vector3.Lerp (mainRigidbody.linearVelocity, Vector3.zero + downVelocity, Time.deltaTime * settings.brakeForce);
}
}
clearState ();
currentSpeed = mainRigidbody.linearVelocity.magnitude;
}
void updateSphereState ()
{
Vector3 rotationPlaneNormal = lastContactNormal;
float rotationFactor = 1f;
if (isClimbingActive ()) {
} else if (isSwimmingActive ()) {
rotationFactor = sphereSwimRotation;
} else if (!isOnGround ()) {
if (isOnSteep ()) {
rotationPlaneNormal = lastSteepNormal;
} else {
rotationFactor = sphereAirRotation;
}
}
Vector3 movement = (mainRigidbody.linearVelocity - lastConnectionVelocity) * Time.deltaTime;
movement -= rotationPlaneNormal * Vector3.Dot (movement, rotationPlaneNormal);
float distance = movement.magnitude;
Quaternion rotation = sphereTransform.localRotation;
if (connectedBody != null && connectedBody == previousConnectedBody) {
rotation = Quaternion.Euler (connectedBody.angularVelocity * (Mathf.Rad2Deg * Time.deltaTime)) * rotation;
if (distance < 0.001f) {
sphereTransform.localRotation = rotation;
return;
}
} else if (distance < 0.001f) {
return;
}
float angle = distance * rotationFactor * (180f / Mathf.PI) / sphereRadius;
Vector3 rotationAxis = Vector3.Cross (rotationPlaneNormal, movement).normalized;
rotation = Quaternion.Euler (rotationAxis * angle) * rotation;
if (sphereAlignSpeed > 0f) {
rotation = alignSphereRotation (rotationAxis, rotation, distance);
}
sphereTransform.localRotation = rotation;
}
Quaternion alignSphereRotation (Vector3 rotationAxis, Quaternion rotation, float traveledDistance)
{
Vector3 sphereAxis = sphereTransform.up;
float dot = Mathf.Clamp (Vector3.Dot (sphereAxis, rotationAxis), -1f, 1f);
float angle = Mathf.Acos (dot) * Mathf.Rad2Deg;
float maxAngle = sphereAlignSpeed * traveledDistance;
Quaternion newAlignment = Quaternion.FromToRotation (sphereAxis, rotationAxis) * rotation;
if (angle <= maxAngle) {
return newAlignment;
} else {
return Quaternion.SlerpUnclamped (rotation, newAlignment, maxAngle / angle);
}
}
void clearState ()
{
lastContactNormal = contactNormal;
lastSteepNormal = steepNormal;
lastConnectionVelocity = connectionVelocity;
groundContactCount = steepContactCount = climbContactCount = 0;
contactNormal = steepNormal = climbNormal = Vector3.zero;
connectionVelocity = Vector3.zero;
previousConnectedBody = connectedBody;
connectedBody = null;
submergence = 0f;
}
void fixedUpdateSphereState ()
{
stepsSinceLastGrounded += 1;
stepsSinceLastJump += 1;
velocity = mainRigidbody.linearVelocity;
if (checkClimbing () ||
checkSwimming () ||
isOnGround () ||
snapToGround () ||
checkSteepContacts ()) {
stepsSinceLastGrounded = 0;
if (stepsSinceLastJump > 1) {
jumpPhase = 0;
}
if (groundContactCount > 1) {
contactNormal.Normalize ();
}
} else {
contactNormal = upAxis;
}
if (connectedBody != null) {
if (connectedBody.isKinematic || connectedBody.mass >= mainRigidbody.mass) {
updateConnectionState ();
}
}
}
void updateConnectionState ()
{
if (connectedBody == previousConnectedBody) {
Vector3 connectionMovement = connectedBody.transform.TransformPoint (connectionLocalPosition) - connectionWorldPosition;
connectionVelocity = connectionMovement / Time.deltaTime;
}
connectionWorldPosition = mainRigidbody.position;
connectionLocalPosition = connectedBody.transform.InverseTransformPoint (connectionWorldPosition);
}
bool checkClimbing ()
{
if (isClimbingActive ()) {
if (climbContactCount > 1) {
climbNormal.Normalize ();
float upDot = Vector3.Dot (upAxis, climbNormal);
if (upDot >= minGroundDotProduct) {
climbNormal = lastClimbNormal;
}
}
groundContactCount = 1;
contactNormal = climbNormal;
return true;
}
return false;
}
bool checkSwimming ()
{
if (isSwimmingActive ()) {
groundContactCount = 0;
contactNormal = upAxis;
return true;
}
return false;
}
public override void updateMovingState ()
{
moving = verticalAxis != 0 || horizontalAxis != 0;
}
bool snapToGround ()
{
if (stepsSinceLastGrounded > 1 || stepsSinceLastJump <= 2 || insideWater ()) {
return false;
}
float speed = velocity.magnitude;
if (speed > maxSnapSpeed) {
return false;
}
RaycastHit hit;
if (!Physics.Raycast (mainRigidbody.position, -upAxis, out hit, probeDistance, probeMask, QueryTriggerInteraction.Ignore)) {
return false;
}
Vector3 hitNormal = hit.normal;
float upDot = Vector3.Dot (upAxis, hitNormal);
if (upDot < getMinDot (hit.collider.gameObject.layer)) {
return false;
}
groundContactCount = 1;
contactNormal = hitNormal;
float dot = Vector3.Dot (velocity, hitNormal);
if (dot > 0f) {
velocity = (velocity - hitNormal * dot).normalized * speed;
}
connectedBody = hit.rigidbody;
return true;
}
bool checkSteepContacts ()
{
if (steepContactCount > 1) {
steepNormal.Normalize ();
float upDot = Vector3.Dot (upAxis, steepNormal);
if (upDot >= minGroundDotProduct) {
steepContactCount = 0;
groundContactCount = 1;
contactNormal = steepNormal;
return true;
}
}
return false;
}
void adjustVelocity ()
{
float acceleration, speed;
Vector3 xAxis, zAxis;
float currentMaxSpeeed = maxSpeed * boostInput;
if (isClimbingActive ()) {
acceleration = maxClimbAcceleration;
speed = maxClimbSpeed;
if (usingBoost) {
speed = maxBoostClimbSpeed;
}
xAxis = Vector3.Cross (contactNormal, upAxis);
zAxis = upAxis;
} else if (insideWater ()) {
float swimFactor = Mathf.Min (1f, submergence / swimThreshold);
acceleration = Mathf.LerpUnclamped (isOnGround () ? maxAcceleration : maxAirAcceleration, maxSwimAcceleration, swimFactor);
speed = Mathf.LerpUnclamped (currentMaxSpeeed, maxSwimSpeed, swimFactor);
xAxis = rightAxis;
zAxis = forwardAxis;
} else {
acceleration = isOnGround () ? maxAcceleration : maxAirAcceleration;
float currentClimbSpeed = maxClimbSpeed;
if (usingBoost) {
currentClimbSpeed = maxBoostClimbSpeed;
}
speed = isOnGround () && desiresClimbing ? currentClimbSpeed : currentMaxSpeeed;
xAxis = rightAxis;
zAxis = forwardAxis;
}
xAxis = projectDirectionOnPlane (xAxis, contactNormal);
zAxis = projectDirectionOnPlane (zAxis, contactNormal);
Vector3 relativeVelocity = velocity - connectionVelocity;
Vector3 adjustment;
adjustment.x = moveInput.x * speed - Vector3.Dot (relativeVelocity, xAxis);
adjustment.z = moveInput.z * speed - Vector3.Dot (relativeVelocity, zAxis);
adjustment.y = isSwimmingActive () ? moveInput.y * speed - Vector3.Dot (relativeVelocity, upAxis) : 0f;
adjustment = Vector3.ClampMagnitude (adjustment, acceleration * Time.deltaTime);
velocity += (xAxis * adjustment.x + zAxis * adjustment.z) * boostInput;
if (isSwimmingActive ()) {
velocity += upAxis * adjustment.y;
}
}
bool isOnGround ()
{
return groundContactCount > 0;
}
bool isOnSteep ()
{
return steepContactCount > 0;
}
bool isClimbingActive ()
{
return climbContactCount > 0 && stepsSinceLastJump > 2;
}
bool insideWater ()
{
return submergence > 0f;
}
bool isSwimmingActive ()
{
return submergence >= swimThreshold;
}
public void preventSnapToGround ()
{
stepsSinceLastJump = -1;
}
void OnValidate ()
{
minGroundDotProduct = Mathf.Cos (maxGroundAngle * Mathf.Deg2Rad);
minStairsDotProduct = Mathf.Cos (maxStairsAngle * Mathf.Deg2Rad);
minClimbDotProduct = Mathf.Cos (maxClimbAngle * Mathf.Deg2Rad);
}
void activeJump (Vector3 gravity)
{
Vector3 jumpDirection;
if (isOnGround ()) {
jumpDirection = contactNormal;
} else if (isOnSteep ()) {
jumpDirection = steepNormal;
jumpPhase = 0;
} else if (maxAirJumps > 0 && jumpPhase <= maxAirJumps) {
if (jumpPhase == 0) {
jumpPhase = 1;
}
jumpDirection = contactNormal;
} else {
return;
}
stepsSinceLastJump = 0;
jumpPhase += 1;
float jumpSpeed = Mathf.Sqrt (2f * gravity.magnitude * vehicleControllerSettings.jumpPower);
if (insideWater ()) {
jumpSpeed *= Mathf.Max (0f, 1f - submergence / swimThreshold);
}
jumpDirection = (jumpDirection + upAxis).normalized;
float alignedSpeed = Vector3.Dot (velocity, jumpDirection);
if (alignedSpeed > 0f) {
jumpSpeed = Mathf.Max (jumpSpeed - alignedSpeed, 0f);
}
velocity += jumpDirection * jumpSpeed;
}
void OnCollisionEnter (Collision collision)
{
EvaluateCollision (collision);
}
void OnCollisionStay (Collision collision)
{
EvaluateCollision (collision);
}
void EvaluateCollision (Collision collision)
{
if (isSwimmingActive ()) {
return;
}
int layer = collision.gameObject.layer;
float minDot = getMinDot (layer);
for (int i = 0; i < collision.contacts.Length; i++) {
Vector3 normal = collision.contacts [i].normal;
float upDot = Vector3.Dot (upAxis, normal);
if (upDot >= minDot) {
groundContactCount += 1;
contactNormal += normal;
connectedBody = collision.rigidbody;
} else {
if (upDot > -0.01f) {
steepContactCount += 1;
steepNormal += normal;
if (groundContactCount == 0) {
connectedBody = collision.rigidbody;
}
}
if (desiresClimbing && upDot >= minClimbDotProduct && (climbMask & (1 << layer)) != 0) {
climbContactCount += 1;
climbNormal += normal;
lastClimbNormal = normal;
connectedBody = collision.rigidbody;
}
}
}
}
void OnTriggerEnter (Collider other)
{
if ((waterMask & (1 << other.gameObject.layer)) != 0) {
EvaluateSubmergence (other);
}
}
void OnTriggerStay (Collider other)
{
if ((waterMask & (1 << other.gameObject.layer)) != 0) {
EvaluateSubmergence (other);
}
}
void EvaluateSubmergence (Collider collider)
{
RaycastHit hit;
if (Physics.Raycast (mainRigidbody.position + upAxis * submergenceOffset, -upAxis, out hit, submergenceRange + 1f, waterMask)) {
//, QueryTriggerInteraction.Collide)) {
submergence = 1f - hit.distance / submergenceRange;
} else {
submergence = 1f;
}
if (isSwimmingActive ()) {
connectedBody = collider.attachedRigidbody;
}
}
Vector3 projectDirectionOnPlane (Vector3 direction, Vector3 normal)
{
return (direction - normal * Vector3.Dot (direction, normal)).normalized;
}
float getMinDot (int layer)
{
if ((stairsMask & (1 << layer)) == 0) {
return minGroundDotProduct;
} else {
return minStairsDotProduct;
}
}
//if the vehicle is using the gravity control, set the state in this component
public override void changeGravityControlUse (bool state)
{
base.changeGravityControlUse (state);
}
//the player is getting on or off from the vehicle, so
public override void changeVehicleState ()
{
base.changeVehicleState ();
setDesiresClimbingState (false);
}
public override void setTurnOnState ()
{
}
public override void setTurnOffState (bool previouslyTurnedOn)
{
base.setTurnOffState (previouslyTurnedOn);
if (previouslyTurnedOn) {
}
}
public override bool isDrivingActive ()
{
return driving;
}
public override void setEngineOnOrOffState ()
{
base.setEngineOnOrOffState ();
}
public override void turnOnOrOff (bool state, bool previouslyTurnedOn)
{
base.turnOnOrOff (state, previouslyTurnedOn);
}
//the vehicle has been destroyed, so disabled every component in it
public override void disableVehicle ()
{
base.disableVehicle ();
}
//if the vehicle is using the boost, set the boost particles
public override void usingBoosting ()
{
base.usingBoosting ();
}
//use a jump platform
public void useVehicleJumpPlatform (Vector3 direction)
{
mainRigidbody.AddForce (mainRigidbody.mass * direction, ForceMode.Impulse);
}
public void useJumpPlatformParable (Vector3 direction)
{
Vector3 jumpForce = direction;
mainRigidbody.AddForce (jumpForce, ForceMode.VelocityChange);
}
public void setNewJumpPower (float newJumpPower)
{
vehicleControllerSettings.jumpPower = newJumpPower * 100;
}
public void setOriginalJumpPower ()
{
vehicleControllerSettings.jumpPower = originalJumpPower;
}
//CALL INPUT FUNCTIONS
public override void inputJump ()
{
if (driving && !usingGravityControl && isTurnedOn && vehicleControllerSettings.canJump) {
if (usingHoverBoardWaypoint) {
pickOrReleaseHoverboardVehicle (false, false);
Vector3 totalJumpForce = mainRigidbody.mass * hoverboardJumpForce * (currentNormal + transform.forward);
if (useHoverboardJumpClamp) {
totalJumpForce = Vector3.ClampMagnitude (totalJumpForce, hoverboardJumpClamp);
}
mainRigidbody.AddForce (totalJumpForce, ForceMode.Impulse);
transform.rotation = Quaternion.identity;
return;
}
if (isSwimmingActive ()) {
return;
}
if (desiresClimbing) {
if (!isClimbingActive ()) {
return;
}
} else {
if (!anyOnGround) {
return;
}
}
setDesiresClimbingState (false);
desiredJump = true;
}
}
public override void inputHoldOrReleaseTurbo (bool holdingButton)
{
if (driving && !usingGravityControl && isTurnedOn && !usingHoverBoardWaypoint) {
//boost input
if (holdingButton) {
if (vehicleControllerSettings.canUseBoost) {
usingBoost = true;
//set the camera move away action
mainVehicleCameraController.usingBoost (true, vehicleControllerSettings.boostCameraShakeStateName,
vehicleControllerSettings.useBoostCameraShake, vehicleControllerSettings.moveCameraAwayOnBoost);
}
} else {
//stop boost input
usingBoost = false;
//disable the camera move away action
mainVehicleCameraController.usingBoost (false, vehicleControllerSettings.boostCameraShakeStateName,
vehicleControllerSettings.useBoostCameraShake, vehicleControllerSettings.moveCameraAwayOnBoost);
usingBoosting ();
boostInput = 1;
}
}
}
public override void inputHoldOrReleaseBrake (bool holdingButton)
{
if (driving && !usingGravityControl && isTurnedOn && anyOnGround) {
braking = holdingButton;
}
}
public override void inputSetTurnOnState ()
{
if (driving && !usingGravityControl) {
if (mainVehicleHUDManager.canSetTurnOnState) {
setEngineOnOrOffState ();
}
}
}
public void inputSetClimbState (bool state)
{
if (driving && !usingGravityControl && isTurnedOn) {
if (!useClimbEnabled) {
return;
}
if (isSwimmingActive ()) {
return;
}
setDesiresClimbingState (state);
if (state) {
if (usingBoost) {
mainVehicleCameraController.usingBoost (false, vehicleControllerSettings.boostCameraShakeStateName,
vehicleControllerSettings.useBoostCameraShake, vehicleControllerSettings.moveCameraAwayOnBoost);
}
}
}
}
public void inputToggleClimbState ()
{
if (driving && !usingGravityControl && isTurnedOn) {
inputSetClimbState (!desiresClimbing);
}
}
[System.Serializable]
public class otherVehicleParts
{
public Transform COM;
public GameObject chassis;
}
[System.Serializable]
public class vehicleSettings
{
public LayerMask layer;
public GameObject vehicleCamera;
public float brakeForce = 5;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: e0dd4268f3ede8544a8f6c86250642b7
timeCreated: 1473345364
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/Vehicle Controllers/sphereController.cs
uploadId: 814740

View File

@@ -0,0 +1,108 @@
using UnityEngine;
using System.Collections;
public class turretController : vehicleController
{
[Header ("Custom Settings")]
[Space]
public otherVehicleParts vehicleParts;
public vehicleSettings settings;
float lookAngle;
public override void Awake ()
{
base.Awake ();
}
public override void vehicleUpdate ()
{
if (driving && settings.turretCanRotate) {
horizontalAxis = mainInputActionManager.getPlayerMovementAxis ().x;
if (!useHorizontalInputLerp && !touchPlatform) {
rawAxisValues = mainInputActionManager.getPlayerRawMovementAxis ();
horizontalAxis = rawAxisValues.x;
}
if (mainVehicleCameraController.currentState.useCameraSteer && horizontalAxis == 0) {
localLook = vehicleParts.chassis.transform.InverseTransformDirection (mainVehicleCameraController.getLookDirection ());
if (localLook.z < 0f) {
localLook.x = Mathf.Sign (localLook.x);
}
steering = localLook.x;
steering = Mathf.Clamp (steering, -1f, 1f);
horizontalAxis = steering;
}
lookAngle -= horizontalAxis * settings.rotationSpeed;
if (settings.rotationLimited) {
lookAngle = Mathf.Clamp (lookAngle, -settings.clampTiltXTurret.x, settings.clampTiltXTurret.y);
}
}
}
void FixedUpdate ()
{
if (driving && settings.turretCanRotate) {
Quaternion targetRotation = Quaternion.Euler (0, -lookAngle, 0);
vehicleParts.chassis.transform.localRotation =
Quaternion.Slerp (vehicleParts.chassis.transform.localRotation, targetRotation, Time.deltaTime * settings.smoothRotationSpeed);
}
}
//the player is getting on or off from the vehicle, so
public override void changeVehicleState ()
{
driving = !driving;
if (!driving) {
StartCoroutine (resetTurretRotation ());
lookAngle = 0;
}
}
//the vehicle has been destroyed, so disabled every component in it
public override void disableVehicle ()
{
//disable the controller
this.enabled = false;
}
//reset the weapon rotation when the player gets off
IEnumerator resetTurretRotation ()
{
Quaternion currentBaseYRotation = vehicleParts.chassis.transform.localRotation;
for (float t = 0; t < 1;) {
t += Time.deltaTime * 3;
vehicleParts.chassis.transform.localRotation = Quaternion.Slerp (currentBaseYRotation, Quaternion.identity, t);
yield return null;
}
}
[System.Serializable]
public class otherVehicleParts
{
public GameObject chassis;
}
[System.Serializable]
public class vehicleSettings
{
public bool turretCanRotate;
public bool rotationLimited;
public float rotationSpeed;
public float smoothRotationSpeed = 5;
public Vector2 clampTiltXTurret;
public GameObject vehicleCamera;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 8498eeb64283e5842a5919aee0e6b02e
timeCreated: 1474133772
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/Vehicle Controllers/turretController.cs
uploadId: 814740

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: b3dabe875e5952a49b96275213338562
timeCreated: 1563666970
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/Vehicle Controllers/vehicleController.cs
uploadId: 814740

View File

@@ -0,0 +1,282 @@
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class hoverBoardWayPoints : MonoBehaviour
{
public float movementSpeed;
public bool moveInOneDirection;
public float forceAtEnd;
public float railsOffset;
public float extraScale;
public float triggerRadius;
public string vehicleTag = "vehicle";
public bool modifyMovementSpeedEnabled = true;
public float maxMovementSpeed = 2;
public float minMovementSpeed = 0.1f;
public float modifyMovementSpeed = 5;
public List<wayPointsInfo> wayPoints = new List<wayPointsInfo> ();
public bool allowMovementOnBothDirections;
public bool showGizmo;
public Color gizmoLabelColor = Color.black;
public float gizmoRadius;
public bool useHandleForVertex;
public float handleRadius;
public Color handleGizmoColor;
public bool showVertexHandles;
public GameObject wayPointElement;
int i;
vehicleHUDManager currentVehicleHUDManager;
vehicleController currentVehicleController;
void OnTriggerEnter (Collider col)
{
bool checkVehicleResult = false;
if (col.gameObject.CompareTag (vehicleTag)) {
checkVehicleResult = true;
}
if (!checkVehicleResult) {
if (applyDamage.isVehicle (col.gameObject)) {
checkVehicleResult = true;
}
}
if (checkVehicleResult) {
currentVehicleController = col.gameObject.GetComponent<vehicleController> ();
if (currentVehicleController == null) {
GameObject newVehicleObject = applyDamage.getVehicle (col.gameObject);
if (newVehicleObject != null) {
currentVehicleController = newVehicleObject.GetComponent<vehicleController> ();
}
}
if (currentVehicleController != null) {
if (currentVehicleController.canUseHoverboardWaypoints ()) {
currentVehicleHUDManager = currentVehicleController.GetComponent<vehicleHUDManager> ();
if (currentVehicleHUDManager.isVehicleBeingDriven ()) {
bool canActivateWaypoint = true;
if (currentVehicleController.isUsingHoverBoardWaypoint ()) {
canActivateWaypoint = false;
}
float lastTimeReleasedFromWaypoint = currentVehicleController.getLastTimeReleasedFromWaypoint ();
if (lastTimeReleasedFromWaypoint > 0 && Time.time < lastTimeReleasedFromWaypoint + 0.7f) {
canActivateWaypoint = false;
}
if (canActivateWaypoint) {
currentVehicleController.receiveWayPoints (this);
currentVehicleController.pickOrReleaseHoverboardVehicle (true, false);
}
}
}
}
}
}
// void OnTriggerExit (Collider col)
// {
// if (col.gameObject.CompareTag ("Player") && inside && !moving) {
// pickOrReleaseVehicle (false, false);
// }
// }
//EDITOR FUNCTIONS
public void addNewWayPoint ()
{
Vector3 newPosition = transform.position;
if (wayPoints.Count > 0) {
newPosition = wayPoints [wayPoints.Count - 1].wayPoint.position + wayPoints [wayPoints.Count - 1].wayPoint.forward;
}
GameObject newWayPoint = (GameObject)Instantiate (wayPointElement, newPosition, Quaternion.identity);
newWayPoint.transform.SetParent (transform);
newWayPoint.name = (wayPoints.Count + 1).ToString ("000");
wayPointsInfo newWayPointInfo = new wayPointsInfo ();
newWayPointInfo.Name = newWayPoint.name;
newWayPointInfo.wayPoint = newWayPoint.transform;
newWayPointInfo.direction = newWayPoint.transform.GetChild (0);
newWayPointInfo.trigger = newWayPoint.GetComponentInChildren<CapsuleCollider> ();
newWayPointInfo.railMesh = newWayPoint.GetComponentInChildren<MeshRenderer> ().gameObject;
wayPoints.Add (newWayPointInfo);
updateComponent ();
}
public void removeWaypoint (int index)
{
wayPointsInfo currentWaypointInfo = wayPoints [index];
DestroyImmediate (currentWaypointInfo.wayPoint.gameObject);
wayPoints.RemoveAt (index);
updateComponent ();
}
public void addNewWayPointAtIndex (int index)
{
Vector3 newPosition = transform.position;
if (wayPoints.Count > 0) {
newPosition = wayPoints [index].wayPoint.position + wayPoints [index].wayPoint.forward;
}
GameObject newWayPoint = (GameObject)Instantiate (wayPointElement, newPosition, Quaternion.identity);
newWayPoint.transform.SetParent (transform);
newWayPoint.name = (index + 1).ToString ("000");
wayPointsInfo newWayPointInfo = new wayPointsInfo ();
newWayPointInfo.Name = newWayPoint.name;
newWayPointInfo.wayPoint = newWayPoint.transform;
newWayPointInfo.direction = newWayPoint.transform.GetChild (0);
newWayPointInfo.trigger = newWayPoint.GetComponentInChildren<CapsuleCollider> ();
newWayPointInfo.railMesh = newWayPoint.GetComponentInChildren<MeshRenderer> ().gameObject;
wayPoints.Insert (index, newWayPointInfo);
renameAllWaypoints ();
updateComponent ();
}
public void selectObjectByIndex (int index)
{
wayPointsInfo currentWayPointsInfo = wayPoints [index];
if (currentWayPointsInfo.wayPoint != null) {
GKC_Utils.setActiveGameObjectInEditor (currentWayPointsInfo.wayPoint.gameObject);
}
}
public void renameAllWaypoints ()
{
for (int i = 0; i < wayPoints.Count; i++) {
if (wayPoints [i].wayPoint != null) {
wayPoints [i].Name = (i + 1).ToString ();
wayPoints [i].wayPoint.name = (i + 1).ToString ("000");
wayPoints [i].wayPoint.SetSiblingIndex (i);
}
}
updateComponent ();
}
public void updateComponent ()
{
GKC_Utils.updateComponent (this);
GKC_Utils.updateDirtyScene ("Update Hoverboard Waypoints Info", gameObject);
}
void OnDrawGizmos ()
{
if (!showGizmo) {
return;
}
if (GKC_Utils.isCurrentSelectionActiveGameObject (gameObject)) {
DrawGizmos ();
}
}
void OnDrawGizmosSelected ()
{
DrawGizmos ();
}
//draw the pivot and the final positions of every door
void DrawGizmos ()
{
//&& !Application.isPlaying
if (showGizmo) {
for (i = 0; i < wayPoints.Count; i++) {
if (wayPoints [i].wayPoint != null && wayPoints [i].direction != null) {
Gizmos.color = Color.yellow;
Gizmos.DrawSphere (wayPoints [i].wayPoint.position, gizmoRadius);
if (i + 1 < wayPoints.Count) {
Gizmos.color = Color.white;
Gizmos.DrawLine (wayPoints [i].wayPoint.position, wayPoints [i + 1].wayPoint.position);
wayPoints [i].direction.LookAt (wayPoints [i + 1].wayPoint.position);
float scaleZ = GKC_Utils.distance (wayPoints [i].wayPoint.position, wayPoints [i + 1].wayPoint.position);
wayPoints [i].direction.localScale = new Vector3 (1, 1, scaleZ + scaleZ * extraScale);
Gizmos.color = Color.green;
Gizmos.DrawLine (wayPoints [i].wayPoint.position, wayPoints [i].wayPoint.position + wayPoints [i].direction.forward);
}
if (i == wayPoints.Count - 1 && (i - 1) >= 0 && i != 0) {
wayPoints [i].direction.rotation = Quaternion.LookRotation (wayPoints [i].wayPoint.position - wayPoints [i - 1].wayPoint.position);
Gizmos.color = Color.green;
Gizmos.DrawLine (wayPoints [i].direction.position, wayPoints [i].direction.position + wayPoints [i].direction.forward);
}
if (i == wayPoints.Count - 1) {
wayPoints [i].direction.localScale = Vector3.one;
}
wayPoints [i].trigger.radius = triggerRadius;
wayPoints [i].railMesh.transform.localPosition = new Vector3 (wayPoints [i].railMesh.transform.localPosition.x, railsOffset, wayPoints [i].railMesh.transform.localPosition.z);
}
}
}
}
[System.Serializable]
public class wayPointsInfo
{
public string Name;
public Transform wayPoint;
public Transform direction;
public CapsuleCollider trigger;
public GameObject railMesh;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 61443d54c38f900498eae5c41064b2b4
timeCreated: 1469062304
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/hoverBoardWayPoints.cs
uploadId: 814740

View File

@@ -0,0 +1,446 @@
using UnityEngine;
using System.Collections;
public class launchTrayectory : MonoBehaviour
{
[Header ("Main Settings")]
[Space]
public LayerMask layer;
public bool showLineRendererEnabled = true;
public float width;
public float numberOfPoints;
public float animationSpeed;
public float tillingOffset;
public bool animateTexture;
public Color textureColor;
public bool useMaxDistanceWhenNoSurfaceFound;
public float maxDistanceWhenNoSurfaceFound;
public bool raycastCheckingEnabled = true;
public bool checkIfLockedCameraActive;
[Space]
[Header ("Other Settings")]
[Space]
public bool checkForPlayerCollider;
public Collider playerCollider;
[Space]
public bool useHoldThrowArmAnimation;
public string actionActiveAnimatorName = "Action Active";
public string holdThrowMeleeWeaponAnimatorName = "Action ID";
public int holdThrowMeleeWeaponAnimatorID;
public string setExitStateOnArmsTriggerName = "Set Exit State On Arms";
[Space]
public bool useHeadTrackCheckingLaunchDirection;
public float headTrackBodyWeightOnAim = 1;
[Space]
[Header ("Show Target Position Icon Settings")]
[Space]
public bool showTargetPositionIcon;
public GameObject targetPositionIcon;
public bool rotateTargetPositionIcon;
public float rotateTargetPositionIconSpeed;
[Space]
[Header ("Debug")]
[Space]
public bool parableEnabled = false;
public bool surfaceFound;
public bool checkBodyAimStateActive;
[Space]
[Header ("Components")]
[Space]
public playerCamera mainPlayerCamera;
public Transform shootPosition;
public GameObject character;
public Transform mainCameraTransform;
public LineRenderer lineRenderer;
public headTrack mainHeadTrack;
public Animator mainAnimator;
[Space]
[Header ("Gizmo Settings")]
[Space]
public bool showGizmo;
float currentAnimationOffset;
Vector3 rayPoint;
RaycastHit hit;
bool rayColliding;
float hitDistance;
Vector3 startPosition;
Vector3 endPosition;
Vector3 currentRendererPosition;
float currentRaycastDistance;
public Vector3 raycastDirection;
Vector3 raycastOrigin;
Ray newRay;
Coroutine mainCoroutine;
bool isPlayerMovingOn3dWorld;
void Start ()
{
changeParableState (false);
}
public void stopUpdateCoroutine ()
{
if (mainCoroutine != null) {
StopCoroutine (mainCoroutine);
}
}
IEnumerator updateCoroutine ()
{
var waitTime = new WaitForFixedUpdate ();
while (true) {
updateTrayectoryState ();
yield return waitTime;
}
}
void updateTrayectoryState ()
{
//if the player is using the barrel launcher
if (parableEnabled) {
//get the start position of the parable
startPosition = shootPosition.position;
if (raycastCheckingEnabled) {
currentRaycastDistance = Mathf.Infinity;
} else {
currentRaycastDistance = maxDistanceWhenNoSurfaceFound;
}
raycastDirection = mainCameraTransform.TransformDirection (Vector3.forward);
raycastOrigin = mainCameraTransform.position;
if (checkIfLockedCameraActive) {
if (mainPlayerCamera != null) {
if (!mainPlayerCamera.isCameraTypeFree () && isPlayerMovingOn3dWorld) {
newRay = mainPlayerCamera.getCameraRaycastDirection ();
raycastDirection = newRay.direction;
raycastOrigin = newRay.origin;
}
}
}
surfaceFound = false;
//check where the camera is looking and
if (Physics.Raycast (raycastOrigin, raycastDirection, out hit, currentRaycastDistance, layer)) {
if (showGizmo) {
Debug.DrawRay (raycastOrigin, raycastDirection * currentRaycastDistance, Color.green);
}
if (checkForPlayerCollider) {
if (playerCollider != null) {
if (hit.collider == playerCollider) {
raycastOrigin = hit.point + raycastDirection * 0.2f;
if (Physics.Raycast (raycastOrigin, raycastDirection, out hit, currentRaycastDistance, layer)) {
surfaceFound = true;
}
} else {
surfaceFound = true;
}
} else {
surfaceFound = true;
}
} else {
surfaceFound = true;
}
if (surfaceFound) {
//enable the linerender
hitDistance = hit.distance;
rayPoint = hit.point;
rayColliding = true;
if (showLineRendererEnabled) {
if (!lineRenderer.enabled) {
lineRenderer.enabled = true;
}
}
}
} else {
if (showGizmo) {
Debug.DrawRay (raycastOrigin, raycastDirection * currentRaycastDistance, Color.red);
}
if (useMaxDistanceWhenNoSurfaceFound) {
hitDistance = maxDistanceWhenNoSurfaceFound;
rayPoint = raycastOrigin + raycastDirection * maxDistanceWhenNoSurfaceFound;
rayColliding = true;
if (showLineRendererEnabled) {
if (!lineRenderer.enabled) {
lineRenderer.enabled = true;
}
}
} else {
//disable it
rayColliding = false;
if (showLineRendererEnabled) {
if (lineRenderer.enabled) {
lineRenderer.enabled = false;
}
}
}
}
if (rayColliding) {
//if the ray detects a surface, set the linerenderer positions and animated it
endPosition = rayPoint;
if (showLineRendererEnabled) {
lineRenderer.positionCount = (int)numberOfPoints + 1;
//get every linerendere position according to the number of points
for (float i = 0; i < numberOfPoints + 1; i++) {
currentRendererPosition = getParablePoint (startPosition, endPosition, i / numberOfPoints);
lineRenderer.SetPosition ((int)i, currentRendererPosition);
}
//animate the texture of the line renderer by changing its offset texture
lineRenderer.startWidth = width;
lineRenderer.endWidth = width;
int propertyNameID = Shader.PropertyToID ("_Color");
if (animateTexture) {
currentAnimationOffset -= animationSpeed * Time.deltaTime * hitDistance * 0.05f;
lineRenderer.material.mainTextureScale = new Vector2 (tillingOffset * hitDistance * 0.2f, 1);
lineRenderer.material.mainTextureOffset = new Vector2 (currentAnimationOffset, lineRenderer.material.mainTextureOffset.y);
if (lineRenderer.material.HasProperty (propertyNameID)) {
lineRenderer.material.color = textureColor;
}
}
}
}
if (showTargetPositionIcon) {
updateShowTargetPositionIcon (rayColliding);
}
}
}
void updateShowTargetPositionIcon (bool surfaceLocated)
{
if (surfaceLocated) {
if (!targetPositionIcon.activeSelf) {
targetPositionIcon.SetActive (true);
}
targetPositionIcon.transform.position = hit.point + hit.normal * 0.08f;
Vector3 targetForwardDirection = Vector3.Cross (targetPositionIcon.transform.right, hit.normal);
Quaternion targetRotation = Quaternion.LookRotation (targetForwardDirection, hit.normal);
targetPositionIcon.transform.rotation = targetRotation;
if (rotateTargetPositionIcon) {
targetPositionIcon.transform.Rotate (0, rotateTargetPositionIconSpeed * Time.deltaTime, 0);
}
} else {
if (targetPositionIcon.activeSelf) {
targetPositionIcon.SetActive (false);
}
}
}
public void changeParableState (bool state)
{
//enable or disable the barrel launcher parable
parableEnabled = state;
if (showLineRendererEnabled) {
if (lineRenderer != null) {
if (parableEnabled) {
lineRenderer.enabled = true;
} else {
lineRenderer.enabled = false;
}
}
}
if (parableEnabled) {
mainCoroutine = StartCoroutine (updateCoroutine ());
} else {
stopUpdateCoroutine ();
if (showTargetPositionIcon) {
if (targetPositionIcon.activeSelf) {
targetPositionIcon.SetActive (false);
}
}
}
if (mainPlayerCamera != null) {
isPlayerMovingOn3dWorld = !mainPlayerCamera.is2_5ViewActive ();
if (!isPlayerMovingOn3dWorld) {
if (useHeadTrackCheckingLaunchDirection) {
if (mainHeadTrack == null) {
mainHeadTrack = GKC_Utils.getCharacterHeadTrack (character);
}
}
checkBodyAimState (state);
}
if (useHoldThrowArmAnimation) {
if (holdThrowMeleeWeaponAnimatorID != 0) {
if (mainAnimator == null) {
mainAnimator = GKC_Utils.getCharacterAnimator (character);
}
if (mainAnimator != null) {
if (state) {
GKC_Utils.resetAnimatorTriggerOnCharacter (character, setExitStateOnArmsTriggerName);
mainAnimator.SetInteger (holdThrowMeleeWeaponAnimatorName, holdThrowMeleeWeaponAnimatorID);
mainAnimator.SetBool (actionActiveAnimatorName, true);
} else {
if (GKC_Utils.isActionActiveOnCharacter (character)) {
GKC_Utils.setAnimatorTriggerOnCharacter (character, setExitStateOnArmsTriggerName);
} else {
mainAnimator.SetInteger (holdThrowMeleeWeaponAnimatorName, 0);
mainAnimator.SetBool (actionActiveAnimatorName, false);
}
}
}
}
}
}
}
void checkBodyAimState (bool state)
{
if (!useHeadTrackCheckingLaunchDirection) {
return;
}
if (mainHeadTrack == null) {
return;
}
if (checkBodyAimStateActive == state) {
return;
}
checkBodyAimStateActive = state;
if (state) {
mainHeadTrack.setCameraBodyWeightValue (headTrackBodyWeightOnAim);
} else {
mainHeadTrack.setOriginalCameraBodyWeightValue ();
}
mainHeadTrack.setHeadTrackActiveWhileAimingState (state);
mainHeadTrack.setCanUseHeadTrackOnLockedCameraActiveState (state);
}
Vector3 getParablePoint (Vector3 start, Vector3 end, float t)
{
//set the height of the parable according to the final position
float value = GKC_Utils.distance (start, end) / 65;
float v0y = Physics.gravity.magnitude * value;
float height = v0y;
//translate to local position, to work correctly with the gravity control in the character
float heightY = Mathf.Abs (transform.InverseTransformDirection (start).y - transform.InverseTransformDirection (end).y);
if (heightY < 0.1f) {
//start and end are roughly level
Vector3 travelDirection = end - start;
Vector3 result = start + t * travelDirection;
result += Mathf.Sin (t * Mathf.PI) * height * character.transform.up;
return result;
} else {
//start and end are not level
Vector3 travelDirection = end - start;
Vector3 startNew = start - transform.InverseTransformDirection (start).y * character.transform.up;
startNew += transform.InverseTransformDirection (end).y * character.transform.up;
Vector3 levelDirection = end - startNew;
Vector3 right = Vector3.Cross (travelDirection, levelDirection);
Vector3 up = Vector3.Cross (right, levelDirection);
if (transform.InverseTransformDirection (end).y > transform.InverseTransformDirection (start).y) {
up = -up;
}
Vector3 result = start + t * travelDirection;
result += (Mathf.Sin (t * Mathf.PI) * height) * up.normalized;
return result;
}
}
public void setMainCameraTransform (Transform newCameraTransform)
{
mainCameraTransform = newCameraTransform;
}
public void setShowLineRendererEnabledState (bool state)
{
showLineRendererEnabled = state;
}
void OnDrawGizmos ()
{
//draw the parable in the editor
if (showGizmo && Application.isPlaying) {
GUI.skin.box.fontSize = 16;
Gizmos.color = Color.red;
Gizmos.DrawLine (startPosition, endPosition);
Vector3 lastP = startPosition;
for (float i = 0; i < numberOfPoints + 1; i++) {
Vector3 p = getParablePoint (startPosition, endPosition, i / numberOfPoints);
Gizmos.color = i % 2 == 0 ? Color.blue : Color.green;
Gizmos.DrawLine (lastP, p);
lastP = p;
}
}
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 22edd35ae22499941a625074c2e81a2c
timeCreated: 1464565199
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/launchTrayectory.cs
uploadId: 814740

View File

@@ -0,0 +1,94 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mainRiderSystem : MonoBehaviour
{
[Header ("Main Rider Settings")]
[Space]
public bool isExternalVehicleController;
public bool vehicleOnlyForOnePlayer = true;
public bool isVehicleOnlyForOnePlayerActive ()
{
return vehicleOnlyForOnePlayer;
}
public virtual GameObject getVehicleCameraGameObject ()
{
return null;
}
public virtual vehicleGravityControl getVehicleGravityControl ()
{
return null;
}
public virtual GameObject getVehicleGameObject ()
{
return null;
}
public virtual void setTriggerToDetect (Collider newCollider)
{
}
public virtual void setPlayerVisibleInVehicleState (bool state)
{
}
public virtual void setResetCameraRotationWhenGetOnState (bool state)
{
}
public virtual void setEjectPlayerWhenDestroyedState (bool state)
{
}
public virtual Transform getCustomVehicleTransform ()
{
return null;
}
public virtual void setEnteringOnVehicleFromDistanceState (bool state)
{
}
public virtual void setCurrentPassenger (GameObject passenger)
{
}
public virtual GameObject getCurrentDriver ()
{
return null;
}
public virtual bool isBeingDrivenActive ()
{
return false;
}
public virtual float getVehicleRadius ()
{
return 0;
}
public virtual bool checkIfDetectSurfaceBelongToVehicle (Collider surfaceFound)
{
return false;
}
public virtual Collider getVehicleCollider ()
{
return null;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: e42e98961b4befe48bc604e3c7d3f192
timeCreated: 1637128656
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/mainRiderSystem.cs
uploadId: 814740

View File

@@ -0,0 +1,397 @@
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class playerHUDManager : MonoBehaviour
{
[Header ("Main Settings")]
[Space]
//this scripts allows to a vehicle to get all the hud elements, so all the sliders values and text info can be showed correctly
public string playerHUDName = "Player Info";
public string playerBarsName = "Player Bars";
public string playerModeName = "Player Mode";
public GameObject freeInteractionDeviceCursor;
public bool useBlurUIPanel = true;
[Space]
[Header ("HUD Element List Settings")]
[Space]
public List<HUDElementInfo> HUDElementInfoList = new List<HUDElementInfo> ();
[Space]
[Header ("HUD Elements")]
[Space]
public GameObject playerHUD;
public GameObject vehicleHUD;
public Slider vehicleHealth;
public Slider vehicleBoost;
public Slider vehicleFuel;
public Slider vehicleAmmo;
public Text weaponName;
public Text ammoInfo;
public GameObject healthContent;
public GameObject energyContent;
public GameObject ammoContent;
public GameObject fuelContent;
public GameObject vehicleCursor;
public Texture defaultVehicleCursor;
public Color defaultVehicleCursorColor;
public Vector2 defaultVehicleCursorSize;
public GameObject speedContent;
public Text currentSpeed;
public GameObject vehicleControlsMenu;
public GameObject vehicleControlsMenuElement;
[HideInInspector] public vehicleHUDElements hudElements;
GameObject currentVehicle;
List<GameObject> actionList = new List<GameObject> ();
vehicleHUDManager currentVehicleHUDManager;
bool fingerPressingTouchPanel;
void Start ()
{
vehicleControlsMenu.SetActive (true);
vehicleControlsMenu.SetActive (false);
hudElements.vehicleHealth = vehicleHealth;
hudElements.vehicleBoost = vehicleBoost;
hudElements.vehicleFuel = vehicleFuel;
hudElements.vehicleAmmo = vehicleAmmo;
hudElements.weaponName = weaponName;
hudElements.ammoInfo = ammoInfo;
hudElements.healthContent = healthContent;
hudElements.energyContent = energyContent;
hudElements.ammoContent = ammoContent;
hudElements.fuelContent = fuelContent;
hudElements.vehicleCursor = vehicleCursor;
hudElements.currentSpeed = currentSpeed;
hudElements.speedContent = speedContent;
hudElements.defaultVehicleCursor = defaultVehicleCursor;
hudElements.defaultVehicleCursorColor = defaultVehicleCursorColor;
hudElements.defaultVehicleCursorSize = defaultVehicleCursorSize;
}
public void setControlList (inputActionManager manager)
{
for (int i = 0; i < actionList.Count; i++) {
Destroy (actionList [i]);
}
actionList.Clear ();
if (!vehicleControlsMenuElement.activeSelf) {
vehicleControlsMenuElement.SetActive (true);
}
if (!vehicleControlsMenu.activeSelf) {
vehicleControlsMenu.SetActive (true);
}
//every key field in the edit input button has an editButtonInput component, so create every of them
for (int i = 0; i < manager.multiAxesList.Count; i++) {
for (int j = 0; j < manager.multiAxesList [i].axes.Count; j++) {
inputActionManager.Axes currentAxes = manager.multiAxesList [i].axes [j];
if (currentAxes.showInControlsMenu) {
GameObject buttonClone = (GameObject)Instantiate (vehicleControlsMenuElement, vehicleControlsMenuElement.transform.position, Quaternion.identity);
buttonClone.transform.SetParent (vehicleControlsMenuElement.transform.parent);
buttonClone.transform.localScale = Vector3.one;
buttonClone.name = currentAxes.Name;
buttonClone.transform.GetChild (0).GetComponent<Text> ().text = currentAxes.Name;
buttonClone.transform.GetChild (1).GetComponentInChildren<Text> ().text = currentAxes.keyButton;
actionList.Add (buttonClone);
}
}
}
//get the scroller in the edit input menu
Scrollbar scroller = vehicleControlsMenu.GetComponentInChildren<Scrollbar> ();
//set the scroller in the top position
scroller.value = 1;
//disable the menu
vehicleControlsMenu.SetActive (false);
vehicleControlsMenuElement.SetActive (false);
}
public void setTouchingMenuPanelState (bool state)
{
fingerPressingTouchPanel = state;
}
public bool isFingerPressingTouchPanel ()
{
return fingerPressingTouchPanel;
}
public void openOrCloseControlsMenu (bool state)
{
if (vehicleControlsMenu.activeSelf != state) {
vehicleControlsMenu.SetActive (state);
}
}
public void setCurrentVehicleHUD (GameObject vehicle)
{
currentVehicle = vehicle;
if (currentVehicle) {
currentVehicleHUDManager = currentVehicle.GetComponent<vehicleHUDManager> ();
} else {
currentVehicleHUDManager = null;
}
}
public void closeControlsMenu ()
{
if (currentVehicleHUDManager != null) {
currentVehicleHUDManager.IKDrivingManager.openOrCloseControlsMenu (false);
}
}
public void destroyCurrentVehicle ()
{
if (currentVehicleHUDManager != null) {
if (!currentVehicleHUDManager.vehicleIsDestroyed () && currentVehicleHUDManager.isVehicleBeingDriven ()) {
currentVehicleHUDManager.destroyVehicle ();
}
}
}
public void damageCurrentVehicle (float damageAmount)
{
if (currentVehicleHUDManager != null) {
if (!currentVehicleHUDManager.vehicleIsDestroyed () && currentVehicleHUDManager.isVehicleBeingDriven ()) {
currentVehicleHUDManager.damageVehicle (damageAmount);
}
}
}
public void takeEnergyCurrentVehicle (float energyAmount)
{
if (currentVehicleHUDManager != null) {
if (!currentVehicleHUDManager.vehicleIsDestroyed () && currentVehicleHUDManager.isVehicleBeingDriven ()) {
currentVehicleHUDManager.removeEnergy (energyAmount);
}
}
}
public void takeFuelCurrentVehicle (float fuelAmount)
{
if (currentVehicleHUDManager != null) {
if (!currentVehicleHUDManager.vehicleIsDestroyed () && currentVehicleHUDManager.isVehicleBeingDriven ()) {
currentVehicleHUDManager.removeFuel (fuelAmount);
}
}
}
public void giveHealthCurrentVehicle (float healthAmount)
{
if (currentVehicleHUDManager != null) {
if (!currentVehicleHUDManager.vehicleIsDestroyed () && currentVehicleHUDManager.isVehicleBeingDriven ()) {
currentVehicleHUDManager.getHealth (healthAmount);
}
}
}
public void giveEnergyCurrentVehicle (float energyAmount)
{
if (currentVehicleHUDManager != null) {
if (!currentVehicleHUDManager.vehicleIsDestroyed () && currentVehicleHUDManager.isVehicleBeingDriven ()) {
currentVehicleHUDManager.getEnergy (energyAmount);
}
}
}
public void giveFuelCurrentVehicle (float fuelAmount)
{
if (currentVehicleHUDManager != null) {
if (!currentVehicleHUDManager.vehicleIsDestroyed () && currentVehicleHUDManager.isVehicleBeingDriven ()) {
currentVehicleHUDManager.getFuel (fuelAmount);
}
}
}
public void setInfiniteHealthCurrentVehicleState (bool state)
{
if (currentVehicleHUDManager != null) {
if (!currentVehicleHUDManager.vehicleIsDestroyed () && currentVehicleHUDManager.isVehicleBeingDriven ()) {
currentVehicleHUDManager.setInvencibleState (state);
}
}
}
public void setInfiniteEnergyCurrentVehicleState (bool state)
{
if (currentVehicleHUDManager != null) {
if (!currentVehicleHUDManager.vehicleIsDestroyed () && currentVehicleHUDManager.isVehicleBeingDriven ()) {
currentVehicleHUDManager.setInfiniteEnergyState (state);
}
}
}
public void setInfiniteFuelCurrentVehicleState (bool state)
{
if (currentVehicleHUDManager != null) {
if (!currentVehicleHUDManager.vehicleIsDestroyed () && currentVehicleHUDManager.isVehicleBeingDriven ()) {
currentVehicleHUDManager.setInfiniteFuelState (state);
}
}
}
public void setInfiniteStatCurrentVehicleState (bool state)
{
setInfiniteHealthCurrentVehicleState (state);
setInfiniteEnergyCurrentVehicleState (state);
setInfiniteFuelCurrentVehicleState (state);
}
public vehicleHUDElements getHudElements ()
{
return hudElements;
}
public GameObject getVehicleCursor ()
{
return hudElements.vehicleCursor;
}
public void setFreeInteractionDeviceCursorActiveState (bool state)
{
if (freeInteractionDeviceCursor != null && freeInteractionDeviceCursor.activeSelf != state) {
freeInteractionDeviceCursor.SetActive (state);
}
}
public void enableOrDisableHUD (bool state)
{
enableOrDisableHUDElement (playerHUDName, state, false);
}
public void enableOrDisablePlayerBars (bool state)
{
enableOrDisableHUDElement (playerBarsName, state, false);
}
public void enableOrDisablePlayerMode (bool state)
{
enableOrDisableHUDElement (playerModeName, state, false);
}
public void enableOrDisableHUDFromEditor (bool state)
{
enableOrDisableHUDElement (playerHUDName, state, true);
}
public void enableOrDisablePlayerBarsFromEditor (bool state)
{
enableOrDisableHUDElement (playerBarsName, state, true);
}
public void enableOrDisablePlayerModeFromEditor (bool state)
{
enableOrDisableHUDElement (playerModeName, state, true);
}
public void enableOrDisableVehicleHUD (bool state)
{
if (vehicleHUD.activeSelf != state) {
vehicleHUD.SetActive (state);
}
}
public void enableHUDElement (string elementName)
{
enableOrDisableHUDElement (elementName, true, false);
}
public void disableHUDElement (string elementName)
{
enableOrDisableHUDElement (elementName, false, false);
}
public void enableHUDElementFromEditor (string elementName)
{
enableOrDisableHUDElement (elementName, true, true);
}
public void disableHUDElementFromEditor (string elementName)
{
enableOrDisableHUDElement (elementName, false, true);
}
public void enableOrDisableHUDElement (string elementName, bool state, bool usedFromEditor)
{
for (int i = 0; i < HUDElementInfoList.Count; i++) {
if (usedFromEditor) {
if (HUDElementInfoList [i].Name.Equals (elementName)) {
if (HUDElementInfoList [i].HUDElementGameObject.activeSelf != state) {
HUDElementInfoList [i].HUDElementGameObject.SetActive (state);
}
HUDElementInfoList [i].HUDElementEnabled = state;
}
} else {
if (HUDElementInfoList [i].HUDElementEnabled && HUDElementInfoList [i].Name.Equals (elementName)) {
if (HUDElementInfoList [i].HUDElementGameObject.activeSelf != state) {
HUDElementInfoList [i].HUDElementGameObject.SetActive (state);
}
}
}
}
}
public bool isHUDElementEnabled (string elementName)
{
for (int i = 0; i < HUDElementInfoList.Count; i++) {
if (HUDElementInfoList [i].HUDElementEnabled && HUDElementInfoList [i].Name.Equals (elementName)) {
return true;
}
}
return false;
}
[System.Serializable]
public class vehicleHUDElements
{
public Slider vehicleHealth;
public Slider vehicleBoost;
public Slider vehicleFuel;
public Slider vehicleAmmo;
public Text weaponName;
public Text ammoInfo;
public GameObject healthContent;
public GameObject energyContent;
public GameObject ammoContent;
public GameObject fuelContent;
public GameObject vehicleCursor;
public Text currentSpeed;
public GameObject speedContent;
public Texture defaultVehicleCursor;
public Color defaultVehicleCursorColor;
public Vector2 defaultVehicleCursorSize;
}
[System.Serializable]
public class HUDElementInfo
{
public string Name;
public bool HUDElementEnabled = true;
public GameObject HUDElementGameObject;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 2d5f668f7a3f3a843a679c47739f6049
timeCreated: 1460577516
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/playerHUDManager.cs
uploadId: 814740

View File

@@ -0,0 +1,255 @@
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.Events;
public class shipInterfaceInfo : MonoBehaviour
{
[Header ("Main Settings")]
[Space]
public bool vehicleInterfaceEnabled = true;
public GameObject vehicle;
public bool compassEnabled;
public string speedExtraString = " km/h";
[Space]
[Header ("Compass Elements")]
[Space]
public RectTransform compassBase;
public RectTransform north;
public RectTransform south;
public RectTransform east;
public RectTransform west;
public RectTransform altitudeMarks;
[Space]
[Header ("Other UI Elements")]
[Space]
public GameObject interfaceCanvas;
public Text pitchValue;
public Text yawValue;
public Text rollValue;
public Text altitudeValue;
public Text velocityValue;
public Text coordinateXValue;
public Text coordinateYValue;
public Text coordinateZValue;
public RectTransform level;
public float altitudeMarkSpeed;
public Slider healthBar;
public Slider energyBar;
public Slider fuelBar;
public Text weaponName;
public Text weaponAmmo;
public Text canLand;
public Text enginesState;
public GameObject healthContent;
public GameObject energyContet;
public GameObject fuelContent;
public GameObject weaponContent;
[Space]
[Header ("Componets")]
[Space]
public vehicleHUDManager HUDManager;
public vehicleGravityControl gravityManager;
public vehicleWeaponSystem weaponManager;
public Rigidbody mainRigidbody;
[Space]
[Header ("Debug")]
[Space]
public bool interfaceActive;
int compassDirection;
int compassDirectionAux;
Vector3 normal;
float currentSpeed;
bool showHealth;
bool showEnergy;
bool showFuel;
bool hasWeapons;
Transform vehicleTransform;
bool weaponsManagerLocated;
bool altitudeMarksLocated;
void Start ()
{
weaponsManagerLocated = weaponManager != null;
altitudeMarksLocated = (altitudeMarks != null);
if (weaponsManagerLocated) {
if (!weaponManager.enabled) {
weaponContent.SetActive (false);
} else {
hasWeapons = true;
}
} else {
if (weaponContent != null) {
weaponContent.SetActive (false);
}
}
healthBar.maxValue = HUDManager.healthAmount;
healthBar.value = healthBar.maxValue;
energyBar.maxValue = HUDManager.boostAmount;
energyBar.value = energyBar.maxValue;
if (!HUDManager.invincible) {
showHealth = true;
} else {
if (healthContent != null) {
healthContent.SetActive (false);
}
}
if (!HUDManager.infiniteBoost) {
showEnergy = true;
} else {
if (energyContet != null) {
energyContet.SetActive (false);
}
}
if (HUDManager.vehicleUseFuel && !HUDManager.infiniteFuel) {
showFuel = true;
} else {
if (fuelContent != null) {
fuelContent.SetActive (false);
}
}
vehicleTransform = vehicle.transform;
enableOrDisableInterface (false);
}
void Update ()
{
if (interfaceActive) {
currentSpeed = mainRigidbody.linearVelocity.magnitude;
if (compassEnabled) {
compassDirection = (int)Mathf.Abs (vehicleTransform.eulerAngles.y);
if (compassDirection > 360) {
compassDirection = compassDirection % 360;
}
compassDirectionAux = compassDirection;
if (compassDirectionAux > 180) {
compassDirectionAux = compassDirectionAux - 360;
}
north.anchoredPosition = new Vector2 (-compassDirectionAux * 2, 0);
south.anchoredPosition = new Vector2 (-compassDirection * 2 + 360, 0);
east.anchoredPosition = new Vector2 (-compassDirectionAux * 2 + 180, 0);
west.anchoredPosition = new Vector2 (-compassDirection * 2 + 540, 0);
normal = gravityManager.currentNormal;
if (altitudeMarksLocated) {
float angleX = Mathf.Asin (vehicleTransform.InverseTransformDirection (Vector3.Cross (normal.normalized, vehicleTransform.up)).x) * Mathf.Rad2Deg;
altitudeMarks.anchoredPosition = Vector2.MoveTowards (altitudeMarks.anchoredPosition, new Vector2 (0, angleX), Time.deltaTime * altitudeMarkSpeed);
}
}
if (pitchValue != null) {
pitchValue.text = vehicleTransform.eulerAngles.x.ToString ("0") + " º";
}
if (yawValue != null) {
yawValue.text = vehicleTransform.eulerAngles.y.ToString ("0") + " º";
}
if (rollValue != null) {
rollValue.text = vehicleTransform.eulerAngles.z.ToString ("0") + " º";
}
if (altitudeValue != null) {
altitudeValue.text = vehicleTransform.position.y.ToString ("0") + " m";
}
if (velocityValue != null) {
velocityValue.text = currentSpeed.ToString ("0") + speedExtraString;
}
if (coordinateXValue != null) {
coordinateXValue.text = vehicleTransform.position.x.ToString ("0");
}
if (coordinateYValue != null) {
coordinateYValue.text = vehicleTransform.position.y.ToString ("0");
}
if (coordinateZValue != null) {
coordinateZValue.text = vehicleTransform.position.z.ToString ("0");
}
if (level != null) {
level.localEulerAngles = new Vector3 (0, 0, vehicleTransform.eulerAngles.z);
}
if (hasWeapons && weaponsManagerLocated) {
weaponName.text = weaponManager.getCurrentWeaponName ();
weaponAmmo.text = weaponManager.getCurrentWeaponClipSize () + "/" + weaponManager.getCurrentWeaponRemainAmmo ();
}
if (showHealth) {
healthBar.value = HUDManager.getCurrentHealthAmount ();
}
if (showEnergy) {
energyBar.value = HUDManager.getCurrentEnergyAmount ();
}
if (showFuel) {
fuelBar.value = HUDManager.getCurrentFuelAmount ();
}
}
}
public void enableOrDisableInterface (bool state)
{
if (!vehicleInterfaceEnabled) {
return;
}
interfaceActive = state;
if (interfaceCanvas.activeSelf != interfaceActive) {
interfaceCanvas.SetActive (interfaceActive);
}
}
public void shipCanLand (bool state)
{
if (state) {
canLand.text = "YES";
} else {
canLand.text = "NO";
}
}
public void shipEnginesState (bool state)
{
if (state) {
enginesState.text = "ON";
} else {
enginesState.text = "OFF";
}
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: e26dd092f1d9af346b996e7f51f46024
timeCreated: 1470412058
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/shipInterfaceInfo.cs
uploadId: 814740

View File

@@ -0,0 +1,220 @@
using UnityEngine;
using System.Collections;
public class skidsManager : MonoBehaviour
{
[Header ("Main Settings")]
[Space]
public bool skidsEnabled = true;
public int maxMarks = 1000;
public float markWidth = 0.3f;
public float groundOffset = 0.02f;
public float minDistance = 0.1f;
[Space]
[Header ("Debugs")]
[Space]
public GameObject originalMesh;
markSection[] skidmarks;
bool updated = false;
int numMarks = 0;
Mesh currentMesh;
void Start ()
{
skidmarks = new markSection[maxMarks];
for (int i = 0; i < maxMarks; i++) {
skidmarks [i] = new markSection ();
}
MeshFilter mainMeshFilter = originalMesh.GetComponent<MeshFilter> ();
mainMeshFilter.mesh = new Mesh ();
originalMesh.transform.SetParent (transform);
originalMesh.transform.position = Vector3.zero;
originalMesh.transform.rotation = Quaternion.identity;
currentMesh = mainMeshFilter.mesh;
}
void LateUpdate ()
{
if (!skidsEnabled) {
return;
}
// If the mesh needs to be updated, i.e. a new section has been added,
// the current mesh is removed, and a new mesh for the skidmarks is generated.
if (updated) {
updated = false;
Mesh mesh = currentMesh;
mesh.Clear ();
int segmentCount = 0;
for (int j = 0; j < numMarks && j < maxMarks; j++) {
if (skidmarks [j].lastIndex != -1 && skidmarks [j].lastIndex > numMarks - maxMarks) {
segmentCount++;
}
}
int segmentCountFour = segmentCount * 4;
Vector3[] vertices = new Vector3[segmentCountFour];
Vector3[] normals = new Vector3[segmentCountFour];
Vector4[] tangents = new Vector4[segmentCountFour];
Color[] colors = new Color[segmentCountFour];
Vector2[] uvs = new Vector2[segmentCountFour];
int[] triangles = new int[segmentCount * 6];
segmentCount = 0;
for (int i = 0; i < numMarks && i < maxMarks; i++) {
if (skidmarks [i].lastIndex != -1 && skidmarks [i].lastIndex > numMarks - maxMarks) {
markSection currentMark = skidmarks [i];
markSection last = skidmarks [currentMark.lastIndex % maxMarks];
segmentCountFour = segmentCount * 4;
int verticeIndex1 = segmentCountFour + 0;
int verticeIndex2 = segmentCountFour + 1;
int verticeIndex3 = segmentCountFour + 2;
int verticeIndex4 = segmentCountFour + 3;
vertices [verticeIndex1] = last.positionLeft;
vertices [verticeIndex2] = last.positionRight;
vertices [verticeIndex3] = currentMark.positionLeft;
vertices [verticeIndex4] = currentMark.positionRight;
normals [verticeIndex1] = last.normal;
normals [verticeIndex2] = last.normal;
normals [verticeIndex3] = currentMark.normal;
normals [verticeIndex4] = currentMark.normal;
tangents [verticeIndex1] = last.tangent;
tangents [verticeIndex2] = last.tangent;
tangents [verticeIndex3] = currentMark.tangent;
tangents [verticeIndex4] = currentMark.tangent;
Color lastColor = new Color (0, 0, 0, last.intensity);
Color currentColor = new Color (0, 0, 0, currentMark.intensity);
colors [verticeIndex1] = lastColor;
colors [verticeIndex2] = lastColor;
colors [verticeIndex3] = currentColor;
colors [verticeIndex4] = currentColor;
uvs [verticeIndex1] = Vector2.zero;
uvs [verticeIndex2] = Vector2.right;
uvs [verticeIndex3] = Vector2.up;
uvs [verticeIndex4] = Vector2.one;
int segmentCountSix = segmentCount * 6;
triangles [segmentCountSix + 0] = verticeIndex1;
triangles [segmentCountSix + 2] = verticeIndex2;
triangles [segmentCountSix + 1] = verticeIndex3;
triangles [segmentCountSix + 3] = verticeIndex3;
triangles [segmentCountSix + 5] = verticeIndex2;
triangles [segmentCountSix + 4] = verticeIndex4;
segmentCount++;
}
}
mesh.vertices = vertices;
mesh.normals = normals;
mesh.tangents = tangents;
mesh.colors = colors;
mesh.uv = uvs;
mesh.triangles = triangles;
}
}
// Function called by the wheels that is skidding. Gathers all the information needed to
// create the mesh later. Sets the intensity of the skidmark section b setting the alpha
// of the vertex color.
public int AddSkidMark (Vector3 pos, Vector3 normal, float intensity, int lastIndex)
{
if (!skidsEnabled) {
return -1;
}
int index = numMarks % maxMarks;
if (intensity > 1) {
intensity = 1;
}
if (skidmarks == null || intensity < 0 || index > skidmarks.Length) {
return -1;
}
markSection curr = skidmarks [index];
curr.position = pos + groundOffset * normal;
curr.normal = normal;
curr.intensity = intensity;
curr.lastIndex = lastIndex;
if (lastIndex != -1) {
markSection last = skidmarks [lastIndex % maxMarks];
Vector3 currentPosition = curr.position;
Vector3 dir = (currentPosition - last.position);
Vector3 xDir = Vector3.Cross (dir, normal).normalized;
curr.positionLeft = currentPosition + (markWidth * 0.5f) * xDir;
curr.positionRight = currentPosition - (markWidth * 0.5f) * xDir;
curr.tangent = new Vector4 (xDir.x, xDir.y, xDir.z, 1);
if (last.lastIndex == -1) {
last.tangent = curr.tangent;
last.positionLeft = currentPosition + (markWidth * 0.5f) * xDir;
last.positionRight = currentPosition - (markWidth * 0.5f) * xDir;
}
}
numMarks++;
updated = true;
return numMarks - 1;
}
public void setSkidsEnabledState (bool state)
{
skidsEnabled = state;
}
class markSection
{
public Vector3 position;
public Vector3 normal;
public Vector4 tangent;
public Vector3 positionLeft;
public Vector3 positionRight;
public float intensity;
public int lastIndex;
};
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 4942e5cfa30f8ae4990b49e217f6f5c5
timeCreated: 1474998638
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/skidsManager.cs
uploadId: 814740

View File

@@ -0,0 +1,337 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class vehicleBuilder : MonoBehaviour
{
public string vehicleName;
public LayerMask layerToPlaceVehicle;
public float placeVehicleOffset = 2;
public bool showGizmo;
public bool showGizmoLabel;
public Color gizmoLabelColor = Color.black;
public float gizmoRadius;
public bool useHandle;
public GameObject vehicle;
public GameObject vehicleCamera;
public Transform vehicleViewTransform;
public vehicleHUDManager mainVehicleHUDManager;
public List<vehiclePartInfo> vehiclePartInfoList = new List<vehiclePartInfo> ();
public List<vehicleSettingsInfo> vehicleSettingsInfoList = new List<vehicleSettingsInfo> ();
vehiclePartInfo currentVehiclePartInfo;
vehicleSettingsInfo currentVehicleSettingsInfo;
public bool placeVehicleInScene;
[TextArea (5, 15)] public string buildVehicleExplanation = "IMPORTANT: once you create a new vehicle, add the colliders you need on the vehicle, " +
"set those colliders to the layer 'vehicle' and attach a vehicle damage receiver component. \n\nFinally, go to vehicle hud manager component " +
"and press UPDATE VEHICLE PARTS button";
public void buildVehicle ()
{
adjustVehicleParts ();
completeVehicleBuild ();
resetTemporalVehicleParts ();
adjustVehicleSettings ();
updateComponent ();
}
public void adjustVehicleParts ()
{
for (int i = 0; i < vehiclePartInfoList.Count; i++) {
currentVehiclePartInfo = vehiclePartInfoList [i];
if (currentVehiclePartInfo.useVehiclePart) {
if (currentVehiclePartInfo.newVehicleMesh != null) {
if (currentVehiclePartInfo.currentVehicleMesh != null) {
DestroyImmediate (currentVehiclePartInfo.currentVehicleMesh);
}
for (int j = 0; j < currentVehiclePartInfo.extraVehiclePartMeshesList.Count; j++) {
if (currentVehiclePartInfo.extraVehiclePartMeshesList [j] != null) {
DestroyImmediate (currentVehiclePartInfo.extraVehiclePartMeshesList [j]);
}
}
currentVehiclePartInfo.extraVehiclePartMeshesList.Clear ();
if (currentVehiclePartInfo.temporalVehicleMeshInstantiated) {
currentVehiclePartInfo.currentVehicleMesh = currentVehiclePartInfo.temporalVehicleMesh;
} else {
GameObject newVehiclePart = (GameObject)Instantiate (currentVehiclePartInfo.newVehicleMesh, Vector3.zero, Quaternion.identity);
Transform newVehiclePartTransform = newVehiclePart.transform;
newVehiclePartTransform.SetParent (currentVehiclePartInfo.vehicleMeshParent);
newVehiclePartTransform.localPosition = Vector3.zero;
newVehiclePartTransform.localRotation = Quaternion.identity;
currentVehiclePartInfo.currentVehicleMesh = newVehiclePart;
}
}
} else {
DestroyImmediate (currentVehiclePartInfo.currentVehicleMesh);
for (int j = 0; j < currentVehiclePartInfo.extraVehiclePartMeshesList.Count; j++) {
if (currentVehiclePartInfo.extraVehiclePartMeshesList [j] != null) {
DestroyImmediate (currentVehiclePartInfo.extraVehiclePartMeshesList [j]);
}
}
currentVehiclePartInfo.extraVehiclePartMeshesList.Clear ();
}
currentVehiclePartInfo.newVehicleMesh = null;
if (currentVehiclePartInfo.useVehiclePart) {
if (currentVehiclePartInfo.useEventOnUseVehiclePartEnabled) {
currentVehiclePartInfo.eventOnUseVehiclePartEnabled.Invoke ();
}
} else {
if (currentVehiclePartInfo.useEventOnUseVehiclePartDisabled) {
currentVehiclePartInfo.eventOnUseVehiclePartDisabled.Invoke ();
}
}
}
}
public void adjustVehicleSettings ()
{
for (int i = 0; i < vehicleSettingsInfoList.Count; i++) {
currentVehicleSettingsInfo = vehicleSettingsInfoList [i];
if (currentVehicleSettingsInfo.useBoolState) {
currentVehicleSettingsInfo.eventToSetBoolState.Invoke (currentVehicleSettingsInfo.boolState);
}
if (currentVehicleSettingsInfo.useFloatValue) {
currentVehicleSettingsInfo.eventToSetFloatValue.Invoke (currentVehicleSettingsInfo.floatValue);
}
}
}
public void adjustVehicleSettingsFromEditor ()
{
adjustVehicleSettings ();
}
public void completeVehicleBuild ()
{
mainVehicleHUDManager.setVehicleName (vehicleName);
vehicle.name = vehicleName + " Controller";
vehicleCamera.name = vehicleName + " Camera";
gameObject.name = vehicleName;
mainVehicleHUDManager.setVehicleParts ();
print ("New Vehicle Build: " + mainVehicleHUDManager.getVehicleName ());
if (placeVehicleInScene) {
placeVehicleInCameraPosition ();
}
}
public void setVehicleName (string newValue)
{
vehicleName = newValue;
}
public void resetTemporalVehicleParts ()
{
for (int i = 0; i < vehiclePartInfoList.Count; i++) {
currentVehiclePartInfo = vehiclePartInfoList [i];
currentVehiclePartInfo.temporalVehicleMesh = null;
currentVehiclePartInfo.temporalVehicleMeshInstantiated = false;
currentVehiclePartInfo.temporalNewVehicleMesh = null;
currentVehiclePartInfo.newVehicleMeshPositionOffset = Vector3.zero;
currentVehiclePartInfo.newVehicleMeshEulerOffset = Vector3.zero;
}
}
public void removeTemporalVehicleParts ()
{
for (int i = 0; i < vehiclePartInfoList.Count; i++) {
currentVehiclePartInfo = vehiclePartInfoList [i];
if (currentVehiclePartInfo.temporalVehicleMeshInstantiated) {
DestroyImmediate (currentVehiclePartInfo.temporalVehicleMesh);
currentVehiclePartInfo.temporalVehicleMesh = null;
currentVehiclePartInfo.temporalNewVehicleMesh = null;
}
currentVehiclePartInfo.temporalVehicleMeshInstantiated = false;
currentVehiclePartInfo.newVehicleMeshPositionOffset = Vector3.zero;
currentVehiclePartInfo.newVehicleMeshEulerOffset = Vector3.zero;
if (currentVehiclePartInfo.currentVehicleMesh != null) {
currentVehiclePartInfo.currentVehicleMesh.SetActive (true);
}
currentVehiclePartInfo.newVehicleMesh = null;
currentVehiclePartInfo.useVehiclePart = true;
if (currentVehiclePartInfo.currentVehicleMesh != null) {
currentVehiclePartInfo.currentVehicleMesh.SetActive (true);
}
for (int j = 0; j < currentVehiclePartInfo.extraVehiclePartMeshesList.Count; j++) {
if (currentVehiclePartInfo.extraVehiclePartMeshesList [j] != null) {
currentVehiclePartInfo.extraVehiclePartMeshesList [j].SetActive (true);
}
}
}
updateComponent ();
}
public void getMeshParentTransformValues ()
{
for (int i = 0; i < vehiclePartInfoList.Count; i++) {
currentVehiclePartInfo = vehiclePartInfoList [i];
if (currentVehiclePartInfo.vehicleMeshParent != null) {
currentVehiclePartInfo.originalMeshParentPosition = currentVehiclePartInfo.vehicleMeshParent.localPosition;
currentVehiclePartInfo.originalMeshParentEulerAngles = currentVehiclePartInfo.vehicleMeshParent.localEulerAngles;
}
}
}
public void placeVehicleInCameraPosition ()
{
Camera currentCameraEditor = GKC_Utils.getCameraEditor ();
if (currentCameraEditor != null) {
Vector3 editorCameraPosition = currentCameraEditor.transform.position;
Vector3 editorCameraForward = currentCameraEditor.transform.forward;
RaycastHit hit;
if (Physics.Raycast (editorCameraPosition, editorCameraForward, out hit, Mathf.Infinity, layerToPlaceVehicle)) {
transform.position = hit.point + (Vector3.up * placeVehicleOffset);
}
}
}
public void alignViewWithVehicleCameraPosition ()
{
setEditorCameraPosition (vehicleViewTransform);
}
public void setEditorCameraPosition (Transform transformToUse)
{
GKC_Utils.alignViewToObject (transformToUse);
}
void updateComponent ()
{
GKC_Utils.updateComponent (this);
GKC_Utils.updateDirtyScene ("New Vehicle Created", gameObject);
}
#if UNITY_EDITOR
void OnDrawGizmos ()
{
if (!showGizmo) {
return;
}
if (GKC_Utils.isCurrentSelectionActiveGameObject (gameObject)) {
DrawGizmos ();
}
}
void OnDrawGizmosSelected ()
{
DrawGizmos ();
}
void DrawGizmos ()
{
if (showGizmo) {
for (int i = 0; i < vehiclePartInfoList.Count; i++) {
if (vehiclePartInfoList [i].objectAlwaysUsed && vehiclePartInfoList [i].currentVehicleMesh) {
Gizmos.color = Color.yellow;
Gizmos.DrawSphere (vehiclePartInfoList [i].currentVehicleMesh.transform.position, gizmoRadius);
}
}
}
}
#endif
[System.Serializable]
public class vehicleSettingsInfo
{
public string Name;
public bool useBoolState;
public bool boolState;
public eventParameters.eventToCallWithBool eventToSetBoolState;
public bool useFloatValue;
public float floatValue;
public eventParameters.eventToCallWithAmount eventToSetFloatValue;
public bool expandElement;
}
[System.Serializable]
public class vehiclePartInfo
{
public string Name;
public bool useVehiclePart = true;
public bool moveMeshParentInsteadOfPart;
public Transform vehicleMeshParent;
public GameObject currentVehicleMesh;
public GameObject newVehicleMesh;
public bool objectAlwaysUsed;
public List<GameObject> extraVehiclePartMeshesList = new List<GameObject> ();
public bool temporalVehicleMeshInstantiated;
public GameObject temporalVehicleMesh;
public GameObject temporalNewVehicleMesh;
public bool useEventOnUseVehiclePartEnabled;
public UnityEvent eventOnUseVehiclePartEnabled;
public bool useEventOnUseVehiclePartDisabled;
public UnityEvent eventOnUseVehiclePartDisabled;
public Vector3 newVehicleMeshPositionOffset;
public Vector3 newVehicleMeshEulerOffset;
public Vector3 originalMeshParentPosition;
public Vector3 originalMeshParentEulerAngles;
public bool expandElement;
public bool showHandleTool = true;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: daa852f1fda5ce340862d7d6dc890dc8
timeCreated: 1577756885
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/vehicleBuilder.cs
uploadId: 814740

View File

@@ -0,0 +1,325 @@
using UnityEngine;
using System.Collections;
public class vehicleDamageReceiver : healthManagement
{
[Space]
[Header ("Main Setting")]
[Space]
[Range (1, 10)] public float damageMultiplier = 1;
[Space]
[Header ("Components")]
[Space]
public GameObject vehicle;
public vehicleHUDManager hudManager;
//this script is added to every collider in a vehicle, so when a projectile hits the vehicle, its health component receives the damge
//like this the damage detection is really accurated.
//the function sends the amount of damage, the direction of the projectile, the position where hits, the object that fired the projectile,
//and if the damaged is done just once, like a bullet, or the damaged is constant like a laser
//health and damage management
public void setDamage (float amount, Vector3 fromDirection, Vector3 damagePos, GameObject bulletOwner, GameObject projectile,
bool damageConstant, bool searchClosestWeakSpot, bool damageCanBeBlocked)
{
hudManager.setDamage (amount * damageMultiplier, fromDirection, damagePos, bulletOwner, projectile, damageConstant,
searchClosestWeakSpot, damageCanBeBlocked);
if (useHealthAmountOnSpot) {
checkHealthAmountOnSpot (amount * damageMultiplier);
}
}
public void setHeal (float amount)
{
hudManager.getHealth (amount);
}
public override float getCurrentHealthAmount ()
{
return hudManager.getCurrentHealthAmount ();
}
public float getMaxHealthAmount ()
{
return hudManager.getMaxHealthAmount ();
}
public float getAuxHealthAmount ()
{
return hudManager.getAuxHealthAmount ();
}
public void addAuxHealthAmount (float amount)
{
hudManager.addAuxHealthAmount (amount);
}
//fuel management
public float getCurrentFuelAmount ()
{
return hudManager.getCurrentFuelAmount ();
}
public float getMaxFuelAmount ()
{
return hudManager.getMaxFuelAmount ();
}
public void getFuel (float amount)
{
hudManager.getFuel (amount);
}
public void removeFuel (float amount)
{
hudManager.removeFuel (amount);
}
//destroy vehicle
public void destroyVehicle ()
{
hudManager.destroyVehicle ();
}
//impact decal management
public int getDecalImpactIndex ()
{
return hudManager.getDecalImpactIndex ();
}
//energy management
public void getEnergy (float amount)
{
hudManager.getEnergy (amount);
}
public void removeEnergy (float amount)
{
hudManager.removeEnergy (amount);
}
public float getCurrentEnergyAmount ()
{
return hudManager.getCurrentEnergyAmount ();
}
public float getMaxEnergyAmount ()
{
return hudManager.getMaxEnergyAmount ();
}
public float getAuxEnergyAmount ()
{
return hudManager.getAuxEnergyAmount ();
}
public void addAuxEnergyAmount (float amount)
{
hudManager.addAuxEnergyAmount (amount);
}
public bool isVehicleDestroyed ()
{
return hudManager.destroyed;
}
public void ignoreCollisionWithSolidVehicleColliderList (Collider colliderToIgnore, bool state)
{
hudManager.ignoreCollisionWithSolidVehicleColliderList (colliderToIgnore, state);
}
//set vehicle component
public void setVehicle (GameObject vehicleGameObject, vehicleHUDManager currentVehicleHUDManager)
{
vehicle = vehicleGameObject;
hudManager = currentVehicleHUDManager;
updateComponent ();
}
public void setDamageTargetOverTimeState (float damageOverTimeDelay, float damageOverTimeDuration, float damageOverTimeAmount, float damageOverTimeRate, bool damageOverTimeToDeath, int damageTypeID)
{
hudManager.setDamageTargetOverTimeState (damageOverTimeDelay, damageOverTimeDuration, damageOverTimeAmount, damageOverTimeRate, damageOverTimeToDeath, damageTypeID);
}
public void removeDamagetTargetOverTimeState ()
{
hudManager.stopDamageOverTime ();
}
public vehicleHUDManager getHUDManager ()
{
return hudManager;
}
//Override functions from Health Management
public override void setDamageWithHealthManagement (float damageAmount, Vector3 fromDirection, Vector3 damagePos, GameObject attacker,
GameObject projectile, bool damageConstant, bool searchClosestWeakSpot, bool ignoreShield,
bool ignoreDamageInScreen, bool damageCanBeBlocked, bool canActivateReactionSystemTemporally,
int damageReactionID, int damageTypeID)
{
hudManager.setDamage ((damageAmount * damageMultiplier), fromDirection, damagePos, attacker, projectile, damageConstant,
searchClosestWeakSpot, damageCanBeBlocked);
if (useHealthAmountOnSpot) {
checkHealthAmountOnSpot (damageAmount * damageMultiplier);
}
}
public override bool checkIfDeadWithHealthManagement ()
{
return hudManager.vehicleIsDestroyed ();
}
public override bool checkIfMaxHealthWithHealthManagement ()
{
return hudManager.checkIfMaxHealth ();
}
public override void setDamageTargetOverTimeStateWithHealthManagement (float damageOverTimeDelay, float damageOverTimeDuration, float damageOverTimeAmount,
float damageOverTimeRate, bool damageOverTimeToDeath, int damageTypeID)
{
hudManager.setDamageTargetOverTimeState (damageOverTimeDelay, damageOverTimeDuration, damageOverTimeAmount, damageOverTimeRate, damageOverTimeToDeath, damageTypeID);
}
public override void removeDamagetTargetOverTimeStateWithHealthManagement ()
{
hudManager.stopDamageOverTime ();
}
public override void setHealWithHealthManagement (float healAmount)
{
hudManager.getHealth (healAmount);
}
public override float getCurrentHealthAmountWithHealthManagement ()
{
return hudManager.getCurrentHealthAmount ();
}
public override float getMaxHealthAmountWithHealthManagement ()
{
return hudManager.getMaxHealthAmount ();
}
public override float getAuxHealthAmountWithHealthManagement ()
{
return hudManager.getAuxHealthAmount ();
}
public override void addAuxHealthAmountWithHealthManagement (float amount)
{
hudManager.addAuxHealthAmount (amount);
}
public override float getHealthAmountToPickWithHealthManagement (float amount)
{
return hudManager.getHealthAmountToPick (amount);
}
public override void killCharacterWithHealthManagement (GameObject projectile, Vector3 direction, Vector3 position, GameObject attacker, bool damageConstant)
{
hudManager.destroyVehicle ();
}
public override void killCharacterWithHealthManagement ()
{
hudManager.destroyVehicle ();
}
public override Transform getPlaceToShootWithHealthManagement ()
{
return hudManager.getPlaceToShoot ();
}
public override GameObject getPlaceToShootGameObjectWithHealthManagement ()
{
return hudManager.getPlaceToShoot ().gameObject;
}
public override bool isVehicleWithHealthManagement ()
{
return hudManager.isVehicleWithHealthManagement ();
}
public override GameObject getCharacterOrVehicleWithHealthManagement ()
{
return vehicle;
}
public override void setFuelWithHealthManagement (float fuelAmount)
{
hudManager.getFuel (fuelAmount);
}
public override void removeFuelWithHealthManagement (float fuelAmount)
{
hudManager.removeFuel (fuelAmount);
}
public override float getCurrentFuelAmountWithHealthManagement ()
{
return hudManager.getCurrentFuelAmount ();
}
public override bool checkIfMaxFuelWithHealthManagement ()
{
return hudManager.checkIfMaxFuel ();
}
public override GameObject getVehicleWithHealthManagement ()
{
return vehicle;
}
public override vehicleHUDManager getVehicleHUDManagerWithHealthManagement ()
{
return hudManager;
}
public override GameObject getVehicleDriverWithHealthManagement ()
{
return hudManager.getCurrentDriver ();
}
public override void setEnergyWithHealthManagement (float amount)
{
hudManager.getEnergy (amount);
}
public override void removeEnergyWithHealthManagement (float amount)
{
hudManager.removeEnergy (amount);
}
public override float getCurrentEnergyAmountWithHealthManagement ()
{
return hudManager.getCurrentEnergyAmount ();
}
public override bool checkIfMaxEnergyWithHealthManagement ()
{
return hudManager.checkIfMaxEnergy ();
}
public override int getDecalImpactIndexWithHealthManagement ()
{
return hudManager.getDecalImpactIndex ();
}
public override bool isUseImpactSurfaceActiveWithHealthManagement ()
{
return hudManager.isUseImpactSurfaceActive ();
}
public void updateComponent ()
{
GKC_Utils.updateComponent (this);
GKC_Utils.updateDirtyScene ("Update Damage Receiver", gameObject);
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: cbd9553a1ed2ab142a68adbd46ae1bab
timeCreated: 1460591922
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/vehicleDamageReceiver.cs
uploadId: 814740

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 104e84ee6ca5170419653ba0f4de5060
timeCreated: 1460578019
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/vehicleHUDManager.cs
uploadId: 814740

View File

@@ -0,0 +1,280 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class vehicleInteractionPanelSystem : MonoBehaviour
{
[Header ("Main Settings")]
[Space]
public bool vehicleInteractionEnabled = true;
public string enterVehicleAsDriverInputName = "Enter Vehicle As Driver";
public string enterVehicleAsPassengerInputName = "Enter Vehicle As Passenger";
[Space]
[Header ("Debug")]
[Space]
public bool showDebugPrint;
public bool vehicleDetected;
public bool isVehicleFull;
public bool isVehicleBeingDriven;
public bool arePassengerSeatsFull;
public int numberOfVehicleSeats;
public GameObject currentDeviceDetected;
public GameObject previousDeviceDetected;
public GameObject currentVehicleGameObject;
public IKDrivingSystem currentIKDrivingSystem;
public vehicleHUDManager currentVehicleHUDManager;
[Space]
[Header ("Components")]
[Space]
public playerController mainPlayerController;
public usingDevicesSystem mainUsingDevicesSystem;
public playerInputManager mainPlayerInputManager;
[Space]
[Header ("UI Components")]
[Space]
public List<GameObject> vehicleSeatsAvailableIconList = new List<GameObject> ();
public GameObject vehicleDriverIconPanel;
public GameObject vehiclePassengerIconPanel;
public Text vehicleDriverText;
public Text vehiclePassengerText;
public GameObject vehicleFullPanel;
Coroutine updateCoroutine;
void Start ()
{
if (vehicleInteractionEnabled) {
updateCoroutine = StartCoroutine (updateSystemCoroutine ());
}
}
public void stopUpdateCoroutine ()
{
if (updateCoroutine != null) {
StopCoroutine (updateCoroutine);
}
}
IEnumerator updateSystemCoroutine ()
{
var waitTime = new WaitForFixedUpdate ();
while (true) {
updateSystem ();
yield return waitTime;
}
}
void updateSystem ()
{
if (mainPlayerController.isPlayerDriving ()) {
return;
}
if (mainUsingDevicesSystem.anyDeviceDetected ()) {
currentDeviceDetected = mainUsingDevicesSystem.objectToUse;
if (currentDeviceDetected != previousDeviceDetected) {
previousDeviceDetected = currentDeviceDetected;
setCurrentVehicleDetected (currentDeviceDetected);
}
} else {
if (vehicleDetected) {
setCurrentVehicleDetected (null);
currentDeviceDetected = null;
previousDeviceDetected = null;
}
}
}
public void setCurrentVehicleDetected (GameObject newVehicle)
{
if (!vehicleInteractionEnabled) {
return;
}
currentVehicleGameObject = newVehicle;
vehicleDetected = false;
mainUsingDevicesSystem.setUseDeviceButtonEnabledState (true);
if (currentVehicleGameObject != null) {
if (applyDamage.isVehicle (currentVehicleGameObject)) {
vehicleDetected = true;
currentVehicleHUDManager = currentVehicleGameObject.GetComponent<vehicleHUDManager> ();
if (currentVehicleHUDManager == null) {
return;
}
currentIKDrivingSystem = currentVehicleHUDManager.getIKDrivingSystem ();
numberOfVehicleSeats = currentIKDrivingSystem.getVehicleSeatsAmount ();
for (int i = 0; i < vehicleSeatsAvailableIconList.Count; i++) {
if (i < (numberOfVehicleSeats - 1)) {
vehicleSeatsAvailableIconList [i].SetActive (true);
} else {
vehicleSeatsAvailableIconList [i].SetActive (false);
}
}
isVehicleBeingDriven = currentIKDrivingSystem.isVehicleBeingDriven ();
arePassengerSeatsFull = currentIKDrivingSystem.arePassengerSeatsFull ();
if (vehiclePassengerIconPanel.activeSelf != !arePassengerSeatsFull) {
vehiclePassengerIconPanel.SetActive (!arePassengerSeatsFull);
}
if (vehicleDriverIconPanel.activeSelf != !isVehicleBeingDriven) {
vehicleDriverIconPanel.SetActive (!isVehicleBeingDriven);
}
if (!isVehicleBeingDriven) {
string driverButtonKeyValue = mainPlayerInputManager.getButtonKey (enterVehicleAsDriverInputName);
if (driverButtonKeyValue != "") {
vehicleDriverText.text = driverButtonKeyValue;
}
}
string passengerButtonKeyValue = mainPlayerInputManager.getButtonKey (enterVehicleAsPassengerInputName);
if (passengerButtonKeyValue != "") {
vehiclePassengerText.text = passengerButtonKeyValue;
}
isVehicleFull = currentIKDrivingSystem.isVehicleFull ();
if (vehicleFullPanel.activeSelf != !isVehicleFull) {
vehicleFullPanel.SetActive (!isVehicleFull);
}
mainUsingDevicesSystem.setUseDeviceButtonEnabledState (false);
} else {
}
} else {
}
}
public void inputEnterOnVehicleAsDriver ()
{
if (!vehicleInteractionEnabled) {
return;
}
if (isVehicleFull) {
return;
}
if (isVehicleBeingDriven) {
return;
}
if (mainPlayerController.isPlayerDriving ()) {
return;
}
float lastTimeDriving = mainPlayerController.getLastTimeDriving ();
if (lastTimeDriving > -1) {
if (Time.time < lastTimeDriving + 0.3f) {
if (showDebugPrint) {
print ("trying to enter again on vehicle after getting off in a short amount of time, cancelling");
}
return;
}
}
if (vehicleDetected) {
currentIKDrivingSystem.setDriverExternally (mainPlayerController.gameObject);
mainUsingDevicesSystem.setUseDeviceButtonEnabledState (true);
vehicleDetected = false;
currentDeviceDetected = null;
previousDeviceDetected = null;
}
}
public void inputEnterOnVehicleAsPassenger ()
{
if (!vehicleInteractionEnabled) {
return;
}
if (isVehicleFull) {
return;
}
if (arePassengerSeatsFull) {
return;
}
if (mainPlayerController.isPlayerDriving ()) {
GameObject currentVehicle = mainPlayerController.getCurrentVehicle ();
if (currentVehicle != null) {
mainUsingDevicesSystem.clearDeviceList ();
mainUsingDevicesSystem.addDeviceToList (currentVehicle);
mainUsingDevicesSystem.updateClosestDeviceList ();
mainUsingDevicesSystem.setCurrentVehicle (currentVehicle);
mainUsingDevicesSystem.useCurrentDevice (currentVehicle);
}
return;
}
if (vehicleDetected) {
currentIKDrivingSystem.setPassengerExternally (mainPlayerController.gameObject);
mainUsingDevicesSystem.setUseDeviceButtonEnabledState (true);
vehicleDetected = false;
currentDeviceDetected = null;
previousDeviceDetected = null;
}
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: a55912f334b9f094d925a1836fa54317
timeCreated: 1699211533
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/vehicleInteractionPanelSystem.cs
uploadId: 814740

View File

@@ -0,0 +1,476 @@
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.Events;
public class vehicleInterface : MonoBehaviour
{
public bool interfaceCanBeEnabled = true;
public bool interfaceEnabled;
public GameObject vehicle;
public GameObject interfaceCanvas;
public List<interfaceElement> interfaceElementList = new List<interfaceElement> ();
public bool useInterfacePanelInfoList;
public vehicleHUDManager HUDManager;
public RectTransform interfacePanelParent;
public float movePanelSpeed = 2;
public float rotatePanelSpeed = 2;
public List<interfacePanelInfo> interfacePanelInfoList = new List<interfacePanelInfo> ();
bool startInitialized;
playerInputManager playerInput;
Vector2 axisValues;
RectTransform currentInterfacePanelSelected;
bool interfacePanelSelected;
bool movingPanel;
bool rotatingPanel;
void Start ()
{
if (!interfaceCanBeEnabled) {
setInterfaceCanvasState (false);
}
for (int i = 0; i < interfaceElementList.Count; i++) {
GameObject uiElement = interfaceElementList [i].uiElement;
bool uiElementTypeFound = false;
Toggle currenToggle = uiElement.GetComponent<Toggle> ();
if (currenToggle != null) {
currenToggle.isOn = interfaceElementList [i].currentBoolValue;
uiElementTypeFound = true;
}
if (!uiElementTypeFound) {
Scrollbar currenScroll = uiElement.GetComponent<Scrollbar> ();
if (currenScroll != null) {
if (interfaceElementList [i].containsRange) {
currenScroll.value = interfaceElementList [i].currentAmountValue / interfaceElementList [i].range.y;
} else {
currenScroll.value = interfaceElementList [i].currentAmountValue;
}
uiElementTypeFound = true;
}
}
if (!uiElementTypeFound) {
Slider currenSlider = uiElement.GetComponent<Slider> ();
if (currenSlider != null) {
if (interfaceElementList [i].containsRange) {
currenSlider.value = interfaceElementList [i].currentAmountValue / interfaceElementList [i].range.y;
} else {
currenSlider.value = interfaceElementList [i].currentAmountValue;
}
}
}
if (interfaceElementList [i].containsBool) {
interfaceElementList [i].originalBoolValue = interfaceElementList [i].currentBoolValue;
}
}
enableOrDisableInterface (false);
if (useInterfacePanelInfoList) {
for (int i = 0; i < interfacePanelInfoList.Count; i++) {
interfacePanelInfoList [i].originalPosition = interfacePanelInfoList [i].uiRectTransform.localPosition;
interfacePanelInfoList [i].originalRotation = interfacePanelInfoList [i].uiRectTransform.localRotation;
}
}
}
void Update ()
{
if (interfaceEnabled) {
if (useInterfacePanelInfoList) {
if (interfacePanelSelected) {
axisValues = playerInput.getPlayerMouseAxis ();
if (movingPanel) {
interfacePanelParent.localPosition += (Vector3.right * axisValues.x + Vector3.up * axisValues.y) * movePanelSpeed;
}
if (rotatingPanel) {
interfacePanelParent.localEulerAngles += new Vector3 (axisValues.y, -axisValues.x, 0) * rotatePanelSpeed;
}
}
}
}
if (!startInitialized) {
startInitialized = true;
}
}
public void setInterfaceCanBeEnabledState (bool state)
{
interfaceCanBeEnabled = state;
}
public void enableOrDisableInterface (bool state)
{
if (!interfaceCanBeEnabled) {
return;
}
interfaceEnabled = state;
setInterfaceCanvasState (interfaceEnabled);
if (!interfaceEnabled) {
for (int i = 0; i < interfaceElementList.Count; i++) {
if (interfaceElementList [i].disableWhenVehicleOff) {
GameObject uiElement = interfaceElementList [i].uiElement;
if (interfaceElementList [i].containsBool) {
bool boolValue = interfaceElementList [i].originalBoolValue;
bool uiElementTypeFound = false;
Toggle currenToggle = uiElement.GetComponent<Toggle> ();
if (currenToggle != null) {
currenToggle.isOn = boolValue;
uiElementTypeFound = true;
}
if (!uiElementTypeFound) {
Scrollbar currenScroll = uiElement.GetComponent<Scrollbar> ();
if (currenScroll != null) {
if (boolValue) {
currenScroll.value = 0;
} else {
currenScroll.value = 1;
}
uiElementTypeFound = true;
}
}
if (!uiElementTypeFound) {
Slider currenSlider = uiElement.GetComponent<Slider> ();
if (currenSlider != null) {
if (boolValue) {
currenSlider.value = 0;
} else {
currenSlider.value = 1;
}
uiElementTypeFound = true;
}
}
interfaceElementList [i].currentBoolValue = boolValue;
if (interfaceElementList [i].setValueOnText) {
if (interfaceElementList [i].useCustomValueOnText) {
if (boolValue) {
interfaceElementList [i].valuetText.text = interfaceElementList [i].boolActiveCustomText;
} else {
interfaceElementList [i].valuetText.text = interfaceElementList [i].boolNoActiveCustomText;
}
} else {
interfaceElementList [i].valuetText.text = boolValue.ToString ();
}
}
if (interfaceElementList [i].eventToCallBool.GetPersistentEventCount () > 0) {
interfaceElementList [i].eventToCallBool.Invoke (boolValue);
}
}
}
}
}
}
public void checkPressedUIElememt (GameObject uiElement)
{
if (!startInitialized || !interfaceCanBeEnabled) {
return;
}
for (int i = 0; i < interfaceElementList.Count; i++) {
if (uiElement == interfaceElementList [i].uiElement) {
if (interfaceElementList [i].eventSendValues) {
if (interfaceElementList [i].containsAmount) {
float amountToSend = 0;
bool uiElementTypeFound = false;
Scrollbar currenScroll = uiElement.GetComponent<Scrollbar> ();
if (currenScroll != null) {
if (interfaceElementList [i].containsRange) {
amountToSend = interfaceElementList [i].range.y * currenScroll.value;
} else {
amountToSend = currenScroll.value;
}
uiElementTypeFound = true;
}
if (!uiElementTypeFound) {
Slider currenSlider = uiElement.GetComponent<Slider> ();
if (currenSlider != null) {
if (interfaceElementList [i].containsRange) {
amountToSend = interfaceElementList [i].range.y * currenSlider.value;
} else {
amountToSend = currenSlider.value;
}
uiElementTypeFound = true;
}
}
interfaceElementList [i].currentAmountValue = amountToSend;
if (interfaceElementList [i].setValueOnText) {
interfaceElementList [i].valuetText.text = amountToSend.ToString ("F0");
}
if (interfaceElementList [i].eventToCallAmount.GetPersistentEventCount () > 0) {
interfaceElementList [i].eventToCallAmount.Invoke (amountToSend);
}
}
if (interfaceElementList [i].containsBool) {
bool boolValue = false;
bool uiElementTypeFound = false;
Toggle currenToggle = uiElement.GetComponent<Toggle> ();
if (currenToggle != null) {
boolValue = currenToggle.isOn;
uiElementTypeFound = true;
}
if (!uiElementTypeFound) {
Button currenButton = uiElement.GetComponent<Button> ();
if (currenButton != null) {
boolValue = !interfaceElementList [i].currentBoolValue;
uiElementTypeFound = true;
}
}
if (!uiElementTypeFound) {
Scrollbar currenScroll = uiElement.GetComponent<Scrollbar> ();
if (currenScroll != null) {
if (currenScroll.value == 0) {
boolValue = false;
} else {
boolValue = true;
}
uiElementTypeFound = true;
}
}
if (!uiElementTypeFound) {
Slider currenSlider = uiElement.GetComponent<Slider> ();
if (currenSlider != null) {
if (currenSlider.value == 0) {
boolValue = false;
} else {
boolValue = true;
}
uiElementTypeFound = true;
}
}
if (!uiElementTypeFound) {
RawImage currentRawImage = uiElement.GetComponent<RawImage> ();
if (currentRawImage != null) {
boolValue = !interfaceElementList [i].currentBoolValue;
uiElementTypeFound = true;
}
}
if (!uiElementTypeFound) {
Image currentImage = uiElement.GetComponent<Image> ();
if (currentImage != null) {
boolValue = !interfaceElementList [i].currentBoolValue;
uiElementTypeFound = true;
}
}
interfaceElementList [i].currentBoolValue = boolValue;
if (interfaceElementList [i].setValueOnText) {
if (interfaceElementList [i].useCustomValueOnText) {
if (boolValue) {
interfaceElementList [i].valuetText.text = interfaceElementList [i].boolActiveCustomText;
} else {
interfaceElementList [i].valuetText.text = interfaceElementList [i].boolNoActiveCustomText;
}
} else {
interfaceElementList [i].valuetText.text = boolValue.ToString ();
}
}
if (interfaceElementList [i].eventToCallBool.GetPersistentEventCount () > 0) {
interfaceElementList [i].eventToCallBool.Invoke (boolValue);
}
}
} else {
if (interfaceElementList [i].eventToCall.GetPersistentEventCount () > 0) {
interfaceElementList [i].eventToCall.Invoke ();
}
}
}
}
}
public void setMoveInterfacePanelPressed (RectTransform panelToCheck)
{
checkInterfacePanelInfoPressed (panelToCheck);
movingPanel = !movingPanel;
}
public void setRotateInterfacePanelPressed (RectTransform panelToCheck)
{
checkInterfacePanelInfoPressed (panelToCheck);
rotatingPanel = !rotatingPanel;
}
public void checkInterfacePanelInfoPressed (RectTransform panelToCheck)
{
if (!useInterfacePanelInfoList) {
return;
}
for (int i = 0; i < interfacePanelInfoList.Count; i++) {
if (interfacePanelInfoList [i].uiRectTransform == panelToCheck) {
interfacePanelSelected = !interfacePanelSelected;
if (interfacePanelSelected) {
currentInterfacePanelSelected = panelToCheck;
playerInput = HUDManager.getCurrentDriver ().GetComponent<playerInputManager> ();
interfacePanelParent.position = currentInterfacePanelSelected.position;
interfacePanelParent.rotation = currentInterfacePanelSelected.rotation;
currentInterfacePanelSelected.SetParent (interfacePanelParent);
} else {
currentInterfacePanelSelected.SetParent (interfacePanelInfoList [i].panelParent);
currentInterfacePanelSelected = null;
}
}
}
}
public void resetInterfacePanelInfoPressed (RectTransform panelToCheck)
{
if (!useInterfacePanelInfoList) {
return;
}
for (int i = 0; i < interfacePanelInfoList.Count; i++) {
if (interfacePanelInfoList [i].uiRectTransform == panelToCheck) {
interfacePanelInfoList [i].uiRectTransform.localPosition = interfacePanelInfoList [i].originalPosition;
interfacePanelInfoList [i].uiRectTransform.localRotation = interfacePanelInfoList [i].originalRotation;
}
}
}
public void setInterfaceCanvasState (bool state)
{
if (interfaceCanvas.activeSelf != state) {
interfaceCanvas.SetActive (state);
}
}
public void addInterfaceElement ()
{
interfaceElement newInterfaceElement = new interfaceElement ();
newInterfaceElement.Name = "New Element";
interfaceElementList.Add (newInterfaceElement);
updateComponent ();
}
public void updateComponent ()
{
GKC_Utils.updateComponent (this);
GKC_Utils.updateDirtyScene ("Update vehicle interface ", gameObject);
}
[System.Serializable]
public class interfaceElement
{
public string Name;
public GameObject uiElement;
public UnityEvent eventToCall;
public bool eventSendValues;
public bool containsAmount;
public bool containsRange;
public Vector2 range;
public float currentAmountValue;
public bool containsBool;
public bool disableWhenVehicleOff;
public bool originalBoolValue;
public bool currentBoolValue;
public bool setValueOnText;
public Text valuetText;
public bool useCustomValueOnText;
public string boolActiveCustomText;
public string boolNoActiveCustomText;
[SerializeField] public eventParameters.eventToCallWithAmount eventToCallAmount;
[SerializeField] public eventParameters.eventToCallWithBool eventToCallBool;
}
[System.Serializable]
public class interfacePanelInfo
{
public string Name;
public RectTransform uiRectTransform;
public RectTransform panelParent;
public Vector3 originalPosition;
public Quaternion originalRotation;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 175b126d4188f954993673cea361d282
timeCreated: 1530423463
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/vehicleInterface.cs
uploadId: 814740

View File

@@ -0,0 +1,173 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class vehicleLaser : laser
{
[Space]
[Header ("Main Settings")]
[Space]
public float laserDamage = 0.3f;
public float laserDamageRate = 0.5f;
public bool ignoreShield;
public int damageTypeID = -1;
public bool damageCanBeBlocked = true;
public bool usingCustomRayPosition;
[Space]
[Header ("Components")]
[Space]
public LayerMask layer;
public GameObject hitParticles;
public GameObject hitSparks;
public GameObject vehicle;
public GameObject vehicleCamera;
[Space]
public Transform mainCameraTransform;
public vehicleCameraController vehicleCameraManager;
public vehicleHUDManager vehicleHUD;
public GameObject currentDriver;
RaycastHit hit;
bool laserActive;
Vector3 laserPosition;
float lastTimeDamageActive;
Vector3 customRayPosition;
Vector3 customRayDirection;
bool vehicleCameraManagerLocated;
void Start ()
{
changeLaserState (false);
}
void Update ()
{
if (laserActive) {
//check the hit collider of the raycast
if (vehicleCameraManagerLocated) {
mainCameraTransform = vehicleCameraManager.getCurrentCameraTransform ();
}
Vector3 raycastPosition = mainCameraTransform.position;
Vector3 raycastDirection = mainCameraTransform.forward;
if (usingCustomRayPosition) {
raycastPosition = customRayPosition - customRayDirection * 0.2f;
raycastDirection = customRayDirection;
}
if (Physics.Raycast (raycastPosition, raycastDirection, out hit, Mathf.Infinity, layer)) {
// Debug.DrawRay (transform.position, hit.distance * raycastDirection, Color.red);
Vector3 surfacePoint = hit.point;
// if (usingCustomRayPosition) {
// surfacePoint = customRayPosition;
// }
transform.LookAt (surfacePoint);
if (Time.time > laserDamageRate + lastTimeDamageActive) {
applyDamage.checkHealth (gameObject, hit.collider.gameObject, laserDamage, -transform.forward, (surfacePoint - (hit.normal / 4)),
currentDriver, true, true, ignoreShield, false, damageCanBeBlocked, false, -1, damageTypeID);
lastTimeDamageActive = Time.time;
}
//set the sparks and .he smoke in the hit point
laserDistance = hit.distance;
if (!hitSparks.activeSelf) {
hitSparks.SetActive (true);
}
if (!hitParticles.activeSelf) {
hitParticles.SetActive (true);
}
hitParticles.transform.position = surfacePoint + 0.02f * (transform.position - surfacePoint);
hitParticles.transform.rotation = Quaternion.identity;
hitSparks.transform.rotation = Quaternion.LookRotation (hit.normal, transform.up);
laserPosition = surfacePoint;
} else {
//if the laser does not hit anything, disable the particles and set the hit point
if (hitSparks.activeSelf) {
hitSparks.SetActive (false);
}
if (hitParticles.activeSelf) {
hitParticles.SetActive (false);
}
laserDistance = 1000;
Quaternion lookDir = Quaternion.LookRotation (raycastDirection);
transform.rotation = lookDir;
laserPosition = (laserDistance * transform.forward);
}
usingCustomRayPosition = false;
//set the size of the laser, according to the hit position
lRenderer.positionCount = 2;
lRenderer.SetPosition (0, transform.position);
lRenderer.SetPosition (1, laserPosition);
animateLaser ();
}
}
//enable or disable the vehicle laser
public void changeLaserState (bool state)
{
lRenderer.enabled = state;
laserActive = state;
if (state) {
StartCoroutine (laserAnimation ());
lastTimeDamageActive = 0;
} else {
hitSparks.SetActive (false);
hitParticles.SetActive (false);
}
vehicleCameraManagerLocated = vehicleCameraManager != null;
if (state) {
if (vehicleHUD != null) {
currentDriver = vehicleHUD.getCurrentDriver ();
}
}
}
public void updateCustomRayPosition (Vector3 newPosition, Vector3 newDirection)
{
usingCustomRayPosition = true;
customRayPosition = newPosition;
customRayDirection = newDirection;
}
}

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 7c9ffa67ec1191e47ae3beb41adcb21d
timeCreated: 1461520396
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/vehicleLaser.cs
uploadId: 814740

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: 65a6919c05dffc4408a7b57be7e3d7d2
timeCreated: 1461414855
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 40995
packageName: Game Kit Controller - Shooter Melee Adventure Creator 3D + 2.5D
packageVersion: 3.77g
assetPath: Assets/Game Kit Controller/Scripts/Vehicles/vehicleWeaponSystem.cs
uploadId: 814740