I may be way off here, but I’m extremely new to Unity and C#. ( but not to game creation and programming in general ).
I’m wanting to point my rigidbody bullet at a certain marker I have on the playfield.
I’m shooting a ray from the cam to what ever it hits in front of me, then I’m placing a pivot at that hit spot. I want to line the bullet coming from my gun to the hit spot.
public void SetupBullet(Vector3 launchForce, float bulletDamage)
{
/// Get Position where shooting at
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hitInfo))
{
// Set the position of the pivot
Globals.piv.transform.position = hitInfo.point; // Set position to location of the raycast hit.
}
//RigidBodyComponent.transform.LookAt(Globals.piv)
DamagePower = bulletDamage;
RigidBodyComponent.AddForce(launchForce);
}
But I cannot figure out how to point the bullet using physics so as to not break the connection.
Do I need to calculate the differences in the two angles then add torque to line it up so that it points to the hit marker?
Rigidbody.MoveRotation
can be used to rotate a rigidbody via the physics API.
I think you’d pretty much need to get a direction from the gun’s barrel, to your target, create a rotation with Quaternion.LookRotation
, and use that to rotate the bullet.
1 Like
Thanks! I’m still reading over the massive API for unity, I didn’t see MoveRotation, big help! tyvm
1 Like
Whoa, after trying to get this to work for about 6 hours i’m, no further.
I think a better way to ask this question would be like this:
“How does one point a rigidbody transform to a spot in 3d space?”
Does Unity support TFrom ?
My post answered that. You need to make a direction from A to B, make a rotation that points to B, then use the rotation to rotate the object you need to.
Basically this:
Vector3 direction = gunPoint - targetPoint;
Quaternion lookRotation = Quaternion.LookRotation(direction);
bullet.Rigidbody.MoveRotation(lookRotation);
Where gunPoint
is the end of the barrel, targetPoint
is the position in the world you worked out, and bullet
is a component on your bullet prefab you have instantiated, which has a reference to it’s rigidbody.
1 Like
Thanks a lot, in past engines I’ve always been on top with physics routines… just trying to get the right commands and api calls down in Unity to do what is floating in my head. You have helped me take a huge leap forward in that direction…
Thanks again my friend. I only hope to one day be able to help the next fella in line. hehe
1 Like