C# Game Programming Cookbook for Unity 3D / Программирование игр на Unity 3D C#. Книга готовых решений.: 5.3 Колесный транспорт

Оглавление
Английский оригинал Перевод на русский

Сожалеем, но текст оригинала доступен только зарегистрированным пользователям.

Скрипт BaseVehicle.cs используется во встроенной в Unity WheelCollider системе. Компоненты WheelCollider добавляются к gameObjects в местах расположения колёс на корпусе машины.

AntonAV_51 09.12.16 в 13:17

0

BaseVehicle.cs выглядит примерно так:

AntonAV_51 09.12.16 в 13:37

0

using UnityEngine;
using System.Collections;
public class BaseVehicle : ExtendedCustomMonoBehavior
{
public WheelCollider frontWheelLeft;
public WheelCollider frontWheelRight;
public WheelCollider rearWheelLeft;
public WheelCollider rearWheelRight;
public float steerMax = 30f;
public float accelMax = 5000f;
public float brakeMax = 5000f;
public float steer = 0f;
public float motor = 0f;
public float brake = 0f;
public float mySpeed;
public bool isLocked;
[System.NonSerialized]
public Vector3 velo;
[System.NonSerialized]
public Vector3 flatVelo;
public BasePlayerManager myPlayerController;
[System.NonSerialized]
public Keyboard_Input default_input;
public AudioSource engineSoundSource;
public virtual void Start ()
{
Init ();
}
public virtual void Init ()
{ // cache the usual suspects
myBody= rigidbody;
myGO= gameObject;
myTransform= transform;
// add default keyboard input
default_input= myGO.AddComponent<Keyboard_Input>();
// cache a reference to the player controller
myPlayerController= myGO.GetComponent<BasePlayerManager>();
// call base class init
myPlayerController.Init();
// with this simple vehicle code, we set the center of mass // low to try to keep the car from toppling over myBody.centerOfMass= new Vector3(0,-4f,0);
// see if we can find an engine sound source, if we need to if( engineSoundSource==null )
{
engineSoundSource= myGO.GetComponent<AudioSource>();
}
}
public void SetUserInput( bool setInput )
{
canControl= setInput;
}
public void SetLock(bool lockState)
{ isLocked = lockState;
}
public virtual void LateUpdate()
{ // we check for input in LateUpdate because Unity recommends
// this
if(canControl)
GetInput();
// update the audio
UpdateEngineAudio();
}
public virtual void FixedUpdate()
{
UpdatePhysics();
}
public virtual void UpdateEngineAudio()
{ // this is just a 'made up' multiplier value applied to
// mySpeed.
engineSoundSource.pitch= 0.5f + ( Mathf.Abs( mySpeed ) *
0.005f );
}
public virtual void UpdatePhysics()
{
CheckLock();
// grab the velocity of the rigidbody and convert it into // flat velocity (remove the Y)
velo= myBody.angularVelocity;
// convert the velocity to local space so we can see how // fast we're moving forward (along the local z axis)
velo= transform.InverseTransformDirection(myBody.velocity);
flatVelo.x= velo.x;
flatVelo.y= 0;
flatVelo.z= velo.z;
// work out our current forward speed
mySpeed= velo.z;
// if we're moving slow, we reverse motorTorque and remove
// brakeTorque so that the car will reverse if( mySpeed<2 )
{
// that is, if we're pressing down the brake key
// (making brake>0)
if( brake>0 )
{
rearWheelLeft.motorTorque = -brakeMax *
brake;
rearWheelRight.motorTorque = -brakeMax * brake;
rearWheelLeft.brakeTorque = 0;
rearWheelRight.brakeTorque = 0;
frontWheelLeft.steerAngle = steerMax * steer;
frontWheelRight.steerAngle = steerMax * steer;
// drop out of this function before applying
// the 'regular' non-reversed values to the
// wheels
return;
}
}
// apply regular movement values to the wheels rearWheelLeft.motorTorque = accelMax * motor;
rearWheelRight.motorTorque = accelMax * motor;
rearWheelLeft.brakeTorque = brakeMax * brake;
rearWheelRight.brakeTorque = brakeMax * brake;
frontWheelLeft.steerAngle = steerMax * steer;
frontWheelRight.steerAngle = steerMax * steer;
}
public void CheckLock()
{
if (isLocked)
{ // control is locked out and we should be stopped steer = 0; brake = 0; motor = 0;
// hold our rigidbody in place (but allow the Y to move so // the car may drop to the ground if it is not exactly // matched to the terrain) Vector3 tempVEC = myBody.velocity; tempVEC.x = 0; tempVEC.z = 0; myBody.velocity = tempVEC;
}
}
public virtual void GetInput()
{ // calculate steering amount steer= Mathf.Clamp( default_input.GetHorizontal() , -1, 1 );
// how much accelerator? Motor= Mathf.Clamp( default_input.GetVertical() , 0, 1 );
// how much brake? Brake= -1 * Mathf.Clamp( default_input.GetVertical() , -1, 0 );
}
}

AntonAV_51 09.12.16 в 13:38

0
Минутку...