Edy's Vehicle Physics汽车物理模拟源码分析

1,镜头跟随源码分析

         LookAt模式关键源码;

            

public override void Update (Transform self, Transform target, Vector3 targetOffset)
		{
		// Position

		if (enableMovement)
			{
			float stepSize = movementSpeed * Time.deltaTime;

			m_position += GetInputForAxis(forwardAxis) * stepSize * new Vector3(self.forward.x, 0.0f, self.forward.z).normalized;
			m_position += GetInputForAxis(sidewaysAxis) * stepSize * self.right;
			m_position += GetInputForAxis(verticalAxis) * stepSize * self.up;
			}

		self.position = Vector3.Lerp(self.position, m_position, movementDamping * Time.deltaTime);

		// Rotation

		if (target != null)
			{
			Quaternion lookAtRotation = Quaternion.LookRotation(target.position + targetOffset - self.position);
			self.rotation = Quaternion.Slerp(self.rotation, lookAtRotation, damping * Time.deltaTime);
			}

		// Zoom

		if (m_camera != null)
			{
			m_fov -= GetInputForAxis(fovAxis) * fovSpeed;
			m_fov = Mathf.Clamp(m_fov, minFov, maxFov);
			m_camera.fieldOfView = Mathf.Lerp(m_camera.fieldOfView, m_fov, fovDamping * Time.deltaTime);
			}
		}

         绿色标记代码表示先获取一个代表摄像机位置指向汽车位置的时的旋转,再将其插值计算后赋值给摄像机自身的rotation,

damping参数使摄像机存在缓冲效果,而并不是实时指向汽车。

         Quaternion.LookRotation方法有两个Vector3类型的参数,第一个参数表示看向的方向,第二个参数起约束作用

默认为Vector3.up.

        蓝色标记代码表示通过鼠标滚轮对摄像机的视野范围进行控制,同时也进行了插值计算。

        

        SmoothFollow模式(平滑跟随);

        以下为自定义Update方法内容

public override void Update (Transform self, Transform target, Vector3 targetOffset)
		{
		if (target == null) return;
		//updatedVelocity为当前帧target的移动速度,m_smoothLastPos保存上一帧的target的移动速度;
		Vector3 updatedVelocity = (target.position + targetOffset - m_smoothLastPos) / Time.deltaTime;
		m_smoothLastPos = target.position + targetOffset;

		updatedVelocity.y = 0.0f;//将y轴上的速度设为0,使得摄像机只会在水平面改变方向;

		if (updatedVelocity.magnitude > 1.0f)
			{
			m_smoothVelocity = Vector3.Lerp(m_smoothVelocity, updatedVelocity, velocityDamping * Time.deltaTime);
			m_smoothTargetAngle = Mathf.Atan2(m_smoothVelocity.x, m_smoothVelocity.z) * Mathf.Rad2Deg;
			}

		if (!followVelocity)
			m_smoothTargetAngle = target.eulerAngles.y;

		float wantedHeight = target.position.y + targetOffset.y + height;

		m_selfRotationAngle = Mathf.LerpAngle(m_selfRotationAngle, m_smoothTargetAngle, rotationDamping * Time.deltaTime);
		m_selfHeight = Mathf.Lerp(m_selfHeight, wantedHeight, heightDamping * Time.deltaTime);
		Quaternion currentRotation = Quaternion.Euler (0, m_selfRotationAngle, 0);//创建一个插值计算后的旋转;

		Vector3 selfPos = target.position + targetOffset;
		selfPos -= currentRotation * Vector3.forward * distance;
		selfPos.y = m_selfHeight;//通过向量运算得到本帧结束时摄像机的位置;

		Vector3 lookAtTarget = target.position + targetOffset + Vector3.up * height * viewHeightRatio;//设置摄像机lookat对象的位置

		if (m_vehicle != null && controller.cameraCollisions)
			{
			if (m_camera != null)
				{//检测self位置和lookAtTarget位置之间是否存在其他物体
				Vector3 origin = lookAtTarget;
				Vector3 path = selfPos - lookAtTarget;
				Vector3 direction = path.normalized;
				float rayDistance = path.magnitude - m_camera.nearClipPlane;
				float radius = m_camera.nearClipPlane * Mathf.Tan(m_camera.fieldOfView * Mathf.Deg2Rad * 0.5f) + 0.1f;

				selfPos = origin + direction * m_vehicle.SphereRaycastOthers(origin, direction, radius, rayDistance, controller.collisionMask);
				}
			else
				{
				selfPos = m_vehicle.RaycastOthers(lookAtTarget, selfPos, controller.collisionMask);
				}
			}

		self.position = selfPos;
		self.LookAt(lookAtTarget);
		}
	}
             原理:



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Vehicle physics package suitable for wide range of vehicles. Realistic, easy to use and heavily customizable. Wheel Controller 3D, a custom in-house wheel solution, has been used for wheel physics while the rest of the system had been written from the ground up. General features: • Fast vehicle setup with quick start video or included manual. • Seven vehicle prefabs of different types are included: sports car, sedan, 8x8 truck, monster truck, tank, city bus and semi with trailer. • Suitable for wide range of applications. • Runs on both desktop and mobile devices. • Uses custom in-house wheel solution – Wheel Controller 3D – for 3D ground detection and high level of customizability. • Per-wheel surface detection based on terrain textures or object tags. Different friction curves and effects for each surface. • Suspend option for inactive vehicles which minimizes impact on performance while keeping basic functionality. • Character vehicle changer that works with any character controller / game object, including other vehicles. • Helper scripts such as analog and digital gauge controllers, camera and vehicle changers, center of mass and downforce adjusters, etc. Vehicle Physics Details: Engine • Realistic engine power and torque calculation with adjustable power curve and RPM range. • Functional forced induction. Transmission • Gear ratios and final gear ratio. • Dynamic shift point based on load. • Three transmission types: Automatic, Automatic Sequential and Manual. • Manual transmission supports both sequential and H-pattern shifting. • Center differential: Open, Limited Slip, Locking or Equal. Axles • Geometry settings for each axle: Steering Angle, Pro/Anti Ackermann Steering, Toe, Camber, Caster and Anti-roll Bar. • Adjustable power, braking and handbrake distribution. • Per-axle differentials: Open, Limited Slip, Locking and Equal. • Supports solid axle (check Monster Truck in the demo). Damage • Optimized queue-based mesh deformation that spreads processing over multiple frames. • Damage influences vehicle performance and handling. Audio • All audio sources are set up automatically. • Sound can be adjusted through Audio Mixer for all vehicles or though inbuilt mixer for each vehicle and each effect individually. • Engine, forced induction, gear change, suspension, surface, skid, crash, air brake, horn and blinker sounds. Effects • Vehicle light system with low beam, high beam, stop and brake lights, blinkers. • Can be used with any number of lights of any type and/or emissive materials. • Persistent and well optimized mesh-based skidmarks. • Exhaust particle effects based on engine state. • Per-wheel dust and smoke particle effects based on surface the wheel is on. Input • Desktop input using standard input manager with mouse steering option. • Mobile input through on-screen steering wheel and pedals or tilt controls. Trailer • Trailer is a vehicle in itself meaning all the effects that work on a vehicle work on a trailer too. • Trailer gets input routed from the vehicle it is attached to which results in functional lights, braking, damage and even steering if needed. • Built-in attach / detach functionality where any vehicle can attach any trailer with correct tag. Fuel • Fuel consumption calculation using engine’s efficiency. • Readouts in l/100km, km/l and US mpg. UI • Universal analog and digital gauge controllers and lights for use in dashboard or HUD. Code • Modular code structure for easy modification and upgrading. • C# source code with XML comments on all public members. • Tooltip explanations for all visible variables. Compatible With Complete Terrain Shader and IK Driver Vehicle Controller European Truck and Trailer and Super Car models provided by GAME READY 3D MODELS . Try it out: Windows 64bit MacOS X 64bit Android (mobile scene) More info: Website Unity Forums YouTube Class Reference Changelog Note: Wheel Controller 3D is included with this asset and its price has been factored in. If you already own WC3D check the upgrade options. If you have any questions. problems or suggestions you can contact us at nwhcoding@gmail.com. Support is free and we always answer within a few hours.
NWH Vehicle Physics 2 是 Unity 一个完整的车辆模拟资源包。 栩栩如生,易于使用,大量可自定义。 主要特点 可轻松快速地设置,自动加载所有默认设置,并使用提醒开发人员所有设置问题的验证系统。 模块化车辆架构。按照需要启用或禁用车辆部件,或者手动或通过内置 LOD 系统。 动力系统解算器具有出色的性能、稳定性和物理精准度。 车辆的各个方面运行时均可调整 - 包括动力系统、悬架、摩擦、特效等。 外部模块系统。根据需要添加或删除功能。模块易于编写,可修改几乎车辆行为的任何部分。 随附并使用车轮控制器 3D,代替车轮碰撞体。它可以提供对整个车轮下半部分的地面检测功能,且高度可自定义,使用高级摩擦模型。 每个车轮表面检测。为每个表面提供不同的摩擦曲线、声音和特效。 基于易于扩展的界面的输入系统,支持标准 Unity 输入、Unity 的新输入系统和移动控制,开箱即用。 支持 Logitech、Thrustmaster 及其他带有力反馈的方向盘。 适用于所有脚本的自定义编辑器可轻松浏览该资源。为此,我们开发出 NUI - 一个编辑器 GUI 框架,以保持贯穿整个资源的一致视觉效果。 支持 'Photon Unity Networking 2' 和‘镜像’多人游戏解决方案。 高度优化的代码可在台式机和移动设备上运行。所有车辆加总起来,台式机演示每帧占总 CPU 时间不到 0.5 毫秒。 演示中所展示的一切均包含在资源包中。 - 包含完整的 C# 源代码。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值