- Home /
Rotating prefab when "created" with mousePosition
Im creating a classic "Carnival" game where you launch a projectile at boxes to knock them of a shelf. The projectile is a prefab and gets "created" and launched straight forward.
I have tried to use transform.localRotation = Quaternion.Euler( Input.mousePosition.y, Input.mousePosition.x, 0.0f)
and then later rb.AddRelativeForce(x,y,z)
but this doesn't work.
How can i fix this problem? Here's my script for the prefab:
public class CannonBallMovement : MonoBehaviour
{
Rigidbody rb;
public GameObject cannonBall;
public float strength;
public float height;
public float mousex;
public float mousey;
private void Awake()
{
mousex = Input.mousePosition.x;
mousey = Input.mousePosition.y;
transform.localRotation = Quaternion.Euler(mousey, mousex, 0f );
rb = gameObject.GetComponent(typeof(Rigidbody)) as Rigidbody;
}
void Start()
{
rb.AddRelativeForce(0.0f, height * Time.deltaTime * 50, strength * Time.deltaTime * 50);
}
}
Answer by joemane22 · Mar 08, 2020 at 07:12 PM
This is the classic problem of look at point and is well documented. The point you want to look at is the mouse position in world space which can be found from Camera.main.ScreenToWorldPoint(Input.mousePosition)
Then you can use transform.LookAt(worldMousePosition) to rotate the object towards that. If you are in 2d you want to only rotate in the z axis so set the x and y axis back to zero.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do i Achieve mesh Extrusion? 2 Answers
Can I make a collider ignore only one other collider? 0 Answers
knockback 3d c# 1 Answer