0
\$\begingroup\$

My goal through this code in C # is that each time the player presses the Q I create a cube at a fixed position given by another object, then begin translating it in a random direction. ie.

  • first press: a cube is created at the spawn point and moves away in direction 1
  • second press: a cube is created at the spawn point and moves away in direction 2
  • third press: a cube is created at the spawn point and moves away in direction 3

I don't understand why the code below does not work:

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


public class spawn_random_trajet : MonoBehaviour {

    public GameObject Spawn, Spawn2;
    public Transform origineSpawn;
    public float moveSpeed=5f;

    void Update () {    
        if (Input.GetKeyDown (KeyCode.Q)) {    
            int random_trajet_x = Random.Range (-10,10);
            int random_trajet_y = Random.Range (-10,10);
            int random_trajet_z = Random.Range (-10,10);

            Spawn2 = Instantiate(
                 Spawn, 
                 origineSpawn.position, 
                 origineSpawn.rotation
            ) as GameObject;

            transform.Translate ( 
                 random_trajet_x*Time.deltaTime*moveSpeed,
                 random_trajet_y*Time.deltaTime*moveSpeed,
                 random_trajet_z*Time.deltaTime*moveSpeed
            );
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ What happens when you run this code? \$\endgroup\$
    – John Smith
    Commented Apr 11, 2019 at 6:44

1 Answer 1

1
\$\begingroup\$

transform.Translate says "move me by this offset now"

It does not say "take the object I just spawned, and start moving it at this velocity, every frame from now into the indefinite future"

Really, you should put the movement behaviour on the object you've spawned, not on the object that spawns it, as I described to you in a previous answer.

public class TranslateOverTime : MonoBehaviour {

    public Vector3 velocity = new Vector3(1, 0, -1);

    void Update() {
        transform.Translate(velocity * Time.deltaTime, Space.Self);
    }
}

Place an instance of this TranslateOverTime script on the prefab object you wish to instantiate.

public class CreateMovingObject : MonoBehaviour {

    public TranslateOverTime prefab;
    public Transform origin;
    public float moveSpeed = 5f;

    void Update () {
        if (Input.GetKeyDown (KeyCode.Q)) {   
            // Create the new object where we want it to be.       
            TranslateOverTime mover = Instantiate(prefab, origin.position, origin.rotation);

            // Assign it a random velocity. Its script will move it from now on.
            mover.velocity = Random.onUnitSphere * moveSpeed;
        }
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .