栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > 其他

Unity 船的控制

其他 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity 船的控制

原理

按下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();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.B) && isOperated == false)
        {
            isOperated = true;
            player.GetComponent().enabled = false;

            player.AddComponent();
            ConstraintSource constraintSource = new ConstraintSource(){
                sourceTransform = transform,
                weight = 1
            };
            player.GetComponent().SetSources(new List(){constraintSource});
            player.GetComponent().SetTranslationOffset(0, new Vector3(0, 0.3f, 0));
            player.GetComponent().constraintActive = true;
        }
        else if(Input.GetKeyDown(KeyCode.B) && isOperated == true)
        {
            isOperated = false;
            player.GetComponent().enabled = true;

            player.GetComponent().SetSources(new List());
            player.GetComponent().constraintActive = false;
            Destroy(player.GetComponent());
        }

        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 水体浮力的实现

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/902366.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号