Unity restricts movement within a range

Unity restricts movement within a range

In this example, we learn the usage of Vector3.ClampMagnitude to limit the movement of the ball within the range.

Put a small ball on the map to let him move, but don't want him to fall, and limit it to the range of a star, as if tied by a rope, it can be achieved in this way.

Demo ball settings

The rigid body hanging on my ball
insert image description here
has a physical friction of 0 to simulate a rope on the pole to keep him within a certain range.

code show as below

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class MoveRange : MonoBehaviour
{
    
    
    public Transform center;
    public float radius;

    Rigidbody rig;

    public float moveSpeed = 2f;
    void Start()
    {
    
    
        rig = gameObject.GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
    
    
        //给小球一个移动速度
        Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        Vector3 nowVelocity = movement * moveSpeed * Time.deltaTime;
        nowVelocity.y = 0f;
        rig.velocity = nowVelocity;

        //限制小球范围
        Vector3 offset = transform.position - center.position;
        transform.position = center.position + Vector3.ClampMagnitude(offset, radius);
    }
}

renderings

Please add a picture description
reference

Guess you like

Origin blog.csdn.net/thinbug/article/details/132151909