<aside> 📄 This script repels the assigned GameObject away from the VR players hand transforms. Make sure the transforms are configured in the inspector and assign the script to the GameObject.
</aside>
using UnityEngine;
public class RepelFromHands : MonoBehaviour
{
public Transform leftHandTransform;
public Transform rightHandTransform;
public float repelForce = 5.0f;
private void Start()
{
// Find hands using their tags or other means
if (leftHandTransform == null)
{
GameObject leftHand = GameObject.FindWithTag("LeftHand");
if (leftHand != null)
{
leftHandTransform = leftHand.transform;
}
}
if (rightHandTransform == null)
{
GameObject rightHand = GameObject.FindWithTag("RightHand");
if (rightHand != null)
{
rightHandTransform = rightHand.transform;
}
}
}
private void Update()
{
if (leftHandTransform != null && rightHandTransform != null)
{
// Calculate the average position of the hands
Vector3 averageHandPosition = (leftHandTransform.position + rightHandTransform.position) / 2f;
// Calculate the direction from the GameObject to the hands
Vector3 repelDirection = transform.position - averageHandPosition;
// Normalize the direction to get a unit vector
repelDirection.Normalize();
// Apply the repelling force in the opposite direction
GetComponent<Rigidbody>().AddForce(repelDirection * repelForce, ForceMode.Force);
}
}
}