- Home /
How to make the player rotate to where an object is being thrown?
I am making a third person game and the player is allowed to pick up and throw a ball. the problem is that when you rotate the camera and cross hair in front or beside the player, the ball goes in the direction but the player does not rotate. Here is my script using UnityEngine; using System.Collections;
public class throwx : MonoBehaviour {
public Rigidbody rb;
public Transform t_Camera; // Drag&Drop your camera over here from the inspector.
private Vector3 v3_Force; // Force reference vector.
public float f_Multiplier; // A multiplier value if the force wouldn't be enough.
public GameObject carryact;
public Transform ball;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (Time.deltaTime == 0f)
return;
if(carryact.activeInHierarchy)
{
if (Input.GetMouseButtonDown(0))
{
v3_Force = t_Camera.forward;
ball.GetComponent<Rigidbody>().AddForce(v3_Force * f_Multiplier, ForceMode.Force);
}
}
}
}
Answer by dan_wipf · Jan 14, 2019 at 09:17 PM
use transform.lookat(vector3 ballposition, vector3.up)
EDIT:
Example for your Question:
Vector3 targetPostition = new Vector3(ball.position.x, transform.position.y, ball.position.z);
transform.LookAt(targetPostition);
sorry for the short answer. if you want to rotate an object towards a another object then use on the transform which you want to adjust rotation transform.LookAt()
then in the () the first thing is either the transform what you want to look at or a vector3 worldposition, in your case ball or ball.position. the second thing is the upward direction of the desired object which is rotated(player) i think vector3.up in your case.
so add this code after you throw the ball:
transform.LookAt(ball,Vector3.up);
Thank you for your help. I put the line of code in and it rotates the player in the opposite direction of where the ball is being thrown and also rotates the player on the y axis. is there a way to make it stay on only the x and z axis and rotate to the right direction?