赞
踩
原理
按下WS键时,给船一个前后方向上的推力
按下AD键时,给船一个围绕Y轴旋转的扭矩
扭矩 Torque
扭矩力,是使物体发生转动的力。
玩家控制
如果进入驾驶状态,则禁用玩家控制脚本,并使用父子约束将玩家固定在船上。
如果退出驾驶状态,则恢复启用玩家控制脚本,销毁父子约束组件。
配置方法
将脚本挂载在船上,并指定玩家对象
还需要限制船的刚体在X、Z轴上的旋转
效果
代码
- 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);
- }
- }
附
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。