- Home /
How to get RigidBodies to LookAt player, while also moving around the surface of a cylinder?
These two scripts (first attached to the cylinder, or tree, and the second to the Rigidbodies, or bugs) control the gravity of the bugs around the tree.
Attached to tree:
public class TreeGravityScript : MonoBehaviour {
public float gravity = -12;
private Transform cylinderTransform;
private Vector3 cylinderAxis = new Vector3(0, -4, 0);
public Transform target;
void Start()
{
cylinderTransform = transform;
}
public void AttractBug(Transform characterTransform)
{
Vector3 gravityUp = Vector3.ProjectOnPlane(characterTransform.position - cylinderTransform.position, cylinderAxis);
Vector3 localUp = characterTransform.up;
characterTransform.GetComponent<Rigidbody>().AddForce(gravityUp * gravity);
Quaternion targetRotation = Quaternion.FromToRotation(localUp, gravityUp) * characterTransform.rotation;
characterTransform.rotation = Quaternion.Slerp(characterTransform.rotation, targetRotation, 50f * Time.deltaTime);
}
}
Attached to bug:
public class BugGravityBody : MonoBehaviour {
public TreeGravityScript attractorPlanet;
private Transform characterTransform;
public Transform target;
void Start()
{
GetComponent<Rigidbody>().useGravity = false;
GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation;
characterTransform = transform;
}
void FixedUpdate()
{
if (attractorPlanet)
{
attractorPlanet.AttractBug(characterTransform);
}
}
}
A simple Vector3.MoveTowards code in a separate script attached to the Bugs controls their movement towards the player. This is what the culmination of these scripts look like:
My problem is getting the bugs to also face towards, and look at, the player while still correctly moving around the tree. (Transform.LookAt does not work, and x-y-z constraints can't be added since movement around the cylinder changes all of these values). Any help would be greatly appreciated!
Answer by Klarzahs · Jan 14, 2019 at 04:04 PM
Hi,
take a look at Quaternion.LookRotation(Up, Forwards). Up would be your inverse gravity /log normal, forward is the direction to the player, which is player.position - bug.position
Thanks for the feedback, I've looked into this and am still unsure of where in my code that this would go to be effective. I have tried inputting it inside and outside of my QuaternionSlerp line, but no difference is made in the bugs movement, any ideas?
Never$$anonymous$$d! I needed to replace the Quaternion.Slerp with the line you suggested. Thanks for the help!