I'm building upon roll a ball tutorial in unity, and I have managed to rotate the camera around the ball just fine with the code below. But there's one problem.
In this code, when I add force to the ball, with W for example, the force will be added in the exact direction the camera is looking at the ball, meaning pushing the ball onto the ground, increasing friction and lowering speed. And if I press S the force will push the ball to the air, lowering friction and making the ball move fast.
So my question is, how can I achieve rotation without this issue?
Code for Camera (CameraController):
public GameObject Player;
private Vector3 offset;
public float cameraSpeed;
private Vector3 point;
static public Vector3 finalMovement;
void Start () {
offset = transform.position - Player.transform.position;
point = Player.transform.position;
transform.LookAt(point);
}
void LateUpdate()
{
point = Player.transform.position;
offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * cameraSpeed, Vector3.up) * offset;
transform.position = point + offset;
transform.LookAt(point);
}
Vector3 movement;
void FixedUpdate()
{
movement = new Vector3();
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
movement = new Vector3(moveHorizontal, 0f, moveVertical);
finalMovement = GetComponent<Camera>().transform.TransformDirection(movement);
}
Code for ball:
public float speed;
void FixedUpdate()
{
rb.AddForce((CameraController.finalMovement) * speed);
}
point
is at method level orpoint
is a propertyVector3 point { get: return Player.transform.position; }
similarmovement
should be declared inside theFixedUpdate()
method. \$\endgroup\$GetComponent<Camera>().transform
is equivalent totransform
alone if this script is on your camera, and throws aNullReferenceException
otherwise, so probably better to use the simpler version. As for what Felsir mentioned, it's a C# Property. \$\endgroup\$