In my game I want player to be connected to another gameobject, so he can't go too far, but can come close to the object. I tried using Spring Joint, but it doesn't allow player to come close to the attached object. Is there any way to do something like this?
CodePudding user response:
Connect the objects together using Hingejoints. Each object will be attached to the other one using its Rigidbody
component.
CodePudding user response:
With Code
We have to draw a circle around the GameObject that you want the player to connect with. We will use the max distance as the radius. If the player gets out of the circle, it will get snapped to the edge of the sphere. Here is the Visual Explanation.
public Transform center; // GameObject to connect
public float maxDistance; // Max distance to move
void LateUpdate()
{
float distanceX = center.position.x - transform.position.x; // Distance between center and new position on X axis
float distanceZ = center.position.z - transform.position.z; // Distance between center and new position on Y axis
float distance = Mathf.Sqrt(distanceX * distanceX distanceZ * distanceZ); // Distance between center and new position
if (distance > maxDistance) // If the distance is greater than max distance
{
float angle = Mathf.Atan2(-distanceZ, -distanceX); // Get the angle between center and new position
float x = center.position.x maxDistance * Mathf.Cos(angle); // Get the new position on X axis
float z = center.position.z maxDistance * Mathf.Sin(angle); // Get the new position on Y axis
transform.position = new Vector3(x, transform.position.y, z); // Move to the new position
}
}