M
M
Max Darkleviathan2021-12-22 11:10:50
C++ / C#
Max Darkleviathan, 2021-12-22 11:10:50

How to set movement along a Bezier curve at application start?

I'm trying to write in Unity.
Built a Bezier curve from 4 points
using these two scripts

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

public static class Bezier
{

    public static Vector3 GetPoint(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t) {
        t = Mathf.Clamp01(t);
        float oneMinusT = 1f - t;
        return
            oneMinusT * oneMinusT * oneMinusT * p0 +
            3f * oneMinusT * oneMinusT * t * p1 +
            3f * oneMinusT * t * t * p2 +
            t * t * t * p3;
    }

    public static Vector3 GetFirstDerivative(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t) {
        t = Mathf.Clamp01(t);
        float oneMinusT = 1f - t;
        return
            3f * oneMinusT * oneMinusT * (p1 - p0) +
            6f * oneMinusT * t * (p2 - p1) +
            3f * t * t * (p3 - p2);
    }


}


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

[ExecuteAlways]
public class BezierTest : MonoBehaviour
{

    public Transform P0;
    public Transform P1;
    public Transform P2;
    public Transform P3;

    [Range(0,1)]
    public float t;

    void Update()
    {
        transform.position = Bezier.GetPoint(P0.position, P1.position, P2.position, P3.position, t);
        transform.rotation = Quaternion.LookRotation(Bezier.GetFirstDerivative(P0.position, P1.position, P2.position, P3.position, t));
    }


    private void OnDrawGizmos() {

        int sigmentsNumber = 20;
        Vector3 preveousePoint = P0.position;

        for (int i = 0; i < sigmentsNumber + 1; i++) {
            float paremeter = (float)i / sigmentsNumber;
            Vector3 point = Bezier.GetPoint(P0.position, P1.position, P2.position, P3.position, paremeter);
            Gizmos.DrawLine(preveousePoint, point);
            preveousePoint = point;
        }

    }

}


How to set the movement along this trajectory at the start of the project?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
Ente, 2021-12-22
@Ente

Use the free plugin from the store - Bézier Path Creator . It already has built-in construction, and finding any position on the curve, and other useful features.

N
Nazar Mokrinsky, 2015-08-08
@nazarpc

You have already asked such a crazy question, and even chose the answer.
There is a list of bots - analyze the User Agent, but if the search engines notice (more precisely, not if, but when - most likely right away) - you will receive personal sanctions for the site.

D
Dimonchik, 2015-08-08
@dimonchik2013

throw PR out of your head, there is none and it has never been
more accurate, you will never affect the one that is, by definition

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question