- Home /
The question is answered, right answer was accepted
I need help making a script of falling objects
So i am making a game where there are falling rocks and you need to avoid them, my problem is i have tried various scripts but nothing has worked i need help making a script for rocks to fall randomly in different places. I use C#
Answer by sparkzbarca · Dec 30, 2017 at 07:08 AM
well first you'll need to create a prefab of a rock.
So create a sphere, attach to it a rigidbody and sphere collider.
Then you'll need to create a script you attach to it that oncollisionenter it damages the player if it's the player and destroys itself if it collides with terrain.
To make rocks fall randomly you'll want to create an empty game object called for example rock spawner.
You'll want to attach to this object a script that takes it's position via it's transform.position and instaniates the rock prefab. you have the gameobject prefab be public so you can just drag and drop the rock you made into it from the editor so something llike
Class RockSpawner(){
public gameobject RockPrefab;
RandomXPos;
RandomZPos;
YPos = transform.position.y; //all rocks spawn from same height.
Transform SpawnLocation;
while(DoSpawnRocks)
{
//insert timer to only run every second or whatever
RandomXPos = //use mathf.rand to pick a random X in the range of the maps width;
RandomZPos = //use mathf.rand to pick a random Z in the range of the maps depth;
SpawnLocation.set(RandomXpos, Ypos, RandomZpos);
Gameobject.Instaniate(RockPrefab, SpawnLocation);
}
You'll notice I didn't write the code to do random numbers for you, nor did I explain how to run code only ever few seconds with a timer.
This isn't mean, it's because coding can be overwhleming but at the same time you really must do some research and put in some work.
googling C# timer function or
unity random number
these things will teach you how to create random numbers or create timers and while guidance is helpful, you'll kind of need to show yourself that you can in some respects teach yourself if you really wish to program.
If you get stuck or something you can post again in here in comments or a new question but most people will not help TOO MUCH if you don't at least post your code even if it's broken. You kind of need to show you tried and don't simply want it all written for you.
Follow this Question
Related Questions
Why does the object keep falling? 2 Answers
Rays drawn using Debug.DrawRay "fall" in editor view 1 Answer
Crouching and falling through floor 0 Answers
Animated physics causes model to go slowly through 1 Answer
Character still falls. 0 Answers