- Home /
3d Gravitate Only when player is near?(No Gravitate from afar)
Hello, I was wondering how can I make an object only gravitate toward the player when they are in the vicinity?(or within range etc) I found this script out of a question on here and I was wondering if it can be modified just to make the object gravitate towards the player only when they come near it.(I don't want to collect the object if I'm half way across the world in-game. Thanks in advance I want to be able to understand this clearly.)
using UnityEngine;
using System.Collections;
public class ObjectPuller : MonoBehaviour
{
public GameObject attractedTo;
public float strengthOfAttraction = 5.0f;
void Start()
{
}
void FixedUpdate()
{
Vector3 direction = attractedTo.transform.position - transform.position;
gameObject.GetComponent<Rigidbody>().AddForce(strengthOfAttraction * direction);
}
}
Answer by psychentist · Nov 06, 2016 at 10:23 AM
Give the object a spherical collider and make sure "isTrigger" is true.
var gravfactor : float = 9.8;
function OnTriggerStay (other : Collider) {
if (other.attachedRigidbody) {
var heading = transform.position - other.gameObject.transform.position;
other.attachedRigidbody.AddForce(heading * (gravfactor/heading.sqrMagnitude * GetComponent.<Rigidbody>().mass * other.gameObject.GetComponent.<Rigidbody>().mass));
}
}
Your answer
Follow this Question
Related Questions
How to add gravity without a rigidbody 2 Answers
A position locked hinge joint with drag and no gravity? 1 Answer
How can I drag an object with touch on X and Z axis without disrupting the gravity of the rigidbody? 0 Answers
Prevent rigidbody with hinge joint from slowing down 1 Answer
Rigidbody with FreezeRotation on x,y,z enabled still rotates whenever in contact with colliders 0 Answers