How to define a motion trajectory?

Hi

I would like to ask how to define the trajectory of motion using unity 3D. I have object 1 and object 2. When the distance is less than a defined threshold, the object 1 has to move to the object 2 along the motion-trajectory from the sketch. How to define this motion trajectory using unity 3D? The motion is realized after pushing a key from the PC keyboard.

Could you please help me to resolve the problem?

That trajectory appears to be a straight line. You can do this trivially by calling MoveTowards in an Update method. (In fact the sample script in the docs there is pretty much exactly what you want.)

1 Like

Hi,

I tried to use MoveTowards but without success. Could you please help me to resolve the problem?
Here is my code:

publicclassNeedleMove : MonoBehaviour {

publicGameObject Point_Sphere;
publicGameObject Cell;

publicTransform target;

publicfloat speed;

// Update is called once per frame

void Update () {

if (Input.GetKey(KeyCode.P))

{
Cell.transform.position = Vector3.MoveTowards(Cell.transform.position, target.position, 10.00f * Time.deltaTime);
}

}

You haven’t described what the problem is. Your code looks correct (assuming you want Cell to move towards target at 10 units/second while the P key is held down).

1 Like

Is that a direct copy and paste? Because there are spaces missing in some very key locations and one bracket is missing.

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

public class NeedleMove : MonoBehaviour
{
    public GameObject Point_Sphere;
    public GameObject Cell;

    public Transform target;

    public float speed;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.P))
        {
            Cell.transform.position = Vector3.MoveTowards(Cell.transform.position, target.position, 10.00f * Time.deltaTime);
        }
    }
}
1 Like

Hi
The problem is that the Cell object doesn’t move to the target position after pressing the key button “P”.

Here are screeshots of my application.



Do you mean while pressing “P”? Because the way you’ve written it, it will only move while the key is held down.

1 Like

Yes
Something is wrong. It doesn’t work while the key is held down.

Is the script attached to anything in the scene?

1 Like

Yes it was. I deselected it but it is still not working. The script is not attached to the cell object. Is it an error?

Put a Debug.Log() statement inside the if condition to make sure it’s getting called.

1 Like

Everything is OK. I wrote the script again.
Thank you for the help.