我是靠谱客的博主 真实巨人,这篇文章主要介绍Unity 船的控制,现在分享给大家,希望可以做个参考。

原理

按下WS键时,给船一个前后方向上的推力
按下AD键时,给船一个围绕Y轴旋转的扭矩

扭矩 Torque

扭矩力,是使物体发生转动的力。

玩家控制

如果进入驾驶状态,则禁用玩家控制脚本,并使用父子约束将玩家固定在船上。

如果退出驾驶状态,则恢复启用玩家控制脚本,销毁父子约束组件。

配置方法

将脚本挂载在船上,并指定玩家对象

还需要限制船的刚体在X、Z轴上的旋转

效果

代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Animations; public class Motorboat : MonoBehaviour { public GameObject player; public float thrustForce = 50000; //推力 public float torque = 5000; //扭矩 bool isOperated = false; private Rigidbody rigidbody; void Start() { rigidbody = GetComponent<Rigidbody>(); } void Update() { if (Input.GetKeyDown(KeyCode.B) && isOperated == false) { isOperated = true; player.GetComponent<PlayerControl>().enabled = false; player.AddComponent<ParentConstraint>(); ConstraintSource constraintSource = new ConstraintSource(){ sourceTransform = transform, weight = 1 }; player.GetComponent<ParentConstraint>().SetSources(new List<ConstraintSource>(){constraintSource}); player.GetComponent<ParentConstraint>().SetTranslationOffset(0, new Vector3(0, 0.3f, 0)); player.GetComponent<ParentConstraint>().constraintActive = true; } else if(Input.GetKeyDown(KeyCode.B) && isOperated == true) { isOperated = false; player.GetComponent<PlayerControl>().enabled = true; player.GetComponent<ParentConstraint>().SetSources(new List<ConstraintSource>()); player.GetComponent<ParentConstraint>().constraintActive = false; Destroy(player.GetComponent<ParentConstraint>()); } Move(); } void Move() { if(!isOperated) return; float v = Input.GetAxis("Vertical"); float h = Input.GetAxis("Horizontal"); rigidbody.AddForce(transform.forward * v * thrustForce); rigidbody.AddTorque(transform.up * h * torque); } }

Unity 水体浮力的实现

最后

以上就是真实巨人最近收集整理的关于Unity 船的控制的全部内容,更多相关Unity内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部