Control of the Unity Ship

principle

When the WS key is pressed, give the boat a thrust in the fore-aft direction.
When the AD key is pressed, give the boat a torque around the Y axis

Torque

Torque is the force that causes an object to rotate.

player control

If driving, disable the player control script and use parent-child constraints to anchor the player to the boat.

If you exit the driving state, the player control script is re-enabled, destroying the parent-child constraint components.

Configuration method

Mount the script on the boat and specify the player object

It is also necessary to limit the rotation of the rigid body of the ship in the X and Z axes

Effect

code

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);
    }
}

attached

The realization of Unity water buoyancy

Guess you like

Origin blog.csdn.net/weixin_43673589/article/details/123469121