- Home /
How to make objects fall when the player gets close
I have a game where you roll a ball around, collect yellow cubes, and avoid obstacles. I want to know how to add objects to fall when the player gets close.
Answer by Gosta · Nov 09, 2016 at 01:45 AM
This requires that IsKinematic is off, since "If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore", and gravity is a force.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))] //Make sure a rigidbody is attached to the falling object
public class fallingScript : MonoBehaviour {
public Transform player; //This creates a slot in the inspector where you can add your player
public float maxDistance = 5f; //This can be changed in the inspector to your liking
private Rigidbody rigidbody;
void Start () {
rigidbody = GetComponent<Rigidbody> ();
rigidbody.useGravity = false;
}
void Update(){
if (Vector3.Distance (player.position, transform.position) < maxDistance) { //transform is the object that this script is attached to
rigidbody.useGravity = true;
}
}
}
Answer by Filhanteraren · Nov 08, 2016 at 07:36 AM
Set the falling object rigidbody to "Is kinematic".
Add a trigger that changes the isKinematic to false when the player enters it.
public Rigidbody FallingObject;
public void OnTriggerEnter(Collider other)
{
if (FallingObject.isKinematic)
FallingObject.isKinematic = false;
}
Error $$anonymous$$essage. Any idea on what I should do?
I created a new script for it, and I can't attach it to anything because there is something wrong with the script.
Answer by jmgek · Nov 08, 2016 at 03:01 AM
There are many different ways (raycast, trigger, distance) but this is a start: https://www.youtube.com/watch?v=CjXlC-rrdDc
There are lots of resources out there.
Answer by EIQUY3 · Nov 08, 2016 at 07:36 AM
You can make an array of all the objects you want to check with player, then you can check distance from player in a for loop. GameObject[] GameObjectArray; for (int i = 0; i < GameObjectArray.Length; i++ ) { float distance = Vector3.Distance(yourPlayer.transform.position,GameObjectArray[i].transform.position); // YourPlayer is name for your player if (distance < 1f) // choose your distance here { // Your Logic here for making objects fall } }
Your answer

Follow this Question
Related Questions
Falling through the floor issue 11 Answers
Cycle Textures Over Time 2 Answers
TriggerEnter, useGravity, Cubes are not falling down 3 Answers
Touch Lag With S2 1 Answer
Trigger Falling Object 1 Answer