-1

Hi im working on a character animation / interaction with the environment. Im trying to spawn rocks of different sizes going from the ground to where the gravity direction is applied.

Im using c# for both of my scripts (character_movements_animation.cs & powerUp.cs)

My question is how to spawn objects around my character and not through it. Im using the code below:

/* Variables Declaration */
public GameObject rock_Small;
public GameObject rock_Medium;
public GameObject rock_Large;

private float posX, posY, posZ;
private bool checkPos = false;
//Use this for initialization
void Start() {
    //Empty for now
}

// Update is called once per frame
void Update() {

    if (Random.Range(0, 100) < 10) {

        checkPos = false;
        posX = this.transform.position.x + Random.Range(-5.0f, 5.0f);
        posY = this.transform.position.y;
        posZ = this.transform.position.z + Random.Range(-5.0f, 5.0f);

        if(posX > 3f && posY > 3f){
            checkPos = true;
        }

        if (checkPos == true) {

            Vector3 newPos = new Vector3(posX, posY, posZ);
            Instantiate(rock_Small, newPos, rock_Small.transform.rotation);
        }

    }
}

Also see the example in the figure. UNITY

Loizos Vasileiou
  • 674
  • 10
  • 37
  • What do you mean by "through it"? Also you might consider a coroutine to do that spawning. It is pretty inefficient to do that code every frame. – Crowcoder Dec 10 '18 at 18:10
  • I updated my question for you. What I want to achieve is when I spawn all the objects I choose, I want them to start rising up from the ground. However, I don't want any of those rocks shown in the figure to go through my character – Loizos Vasileiou Dec 10 '18 at 18:21

1 Answers1

0

Seems like you want to spawn objects around your character, but avoid the character's own volume.

I'd suggest something like this:

var pos = this.transform.position = Random.insideUnitCircle.normlaized * _distance; //how far away from your character. 1, based on your original code

This will create a ring aorund your character. If you want to randomize things further, you can apply smaller random offsets to this value, eg:

var pos = this.transform.position = Random.insideUnitCircle.normlaized * _distance;
pos += Random.insideUnitCircle * _offset; //how wide the ring should be. 0.1 is probably sufficient.
  • 1
    Keep in mind that `Random.insideUnitCircle` can return (0,0) and Unity will noop if you try to normalize it: `Vector2.zero.normalized == Vector2.zero`. It'a very small chance but it can happen. – Foggzie Dec 10 '18 at 19:02
  • @LoizosVasileiou Converting to C# is easy. Replace `var` with the appropriate type. `Vector3` in this case. You also have to define `_distance` and `_offset` yourself. – Draco18s no longer trusts SE Dec 11 '18 at 14:14