Roll a ball to the direction it is facing
Good day everyone, I have a brief question about the player controller and camera rotation. I think this post will be useful in future as I was searching in the internet for lots of answers and tutorials and most of them just covers FPS games where main character is a box or human and it cannot roll.
So I am doing a roll a ball game where player uses joystick to controll the ball. However I want to make camera rotation and after player rotates the camera, ball controller will adjust to this rotation so if the player move joystick forward, the ball will go also forward in the new direction. (Right now it continues to go forward for the previous one). If it is possible, could you please write me the way of solving this problem.
Additional information: I made extra object which is PlayerBody (it is the same ball as the player, but the rotation is frozed and camera is attached to it, because the player ball is rolling and camera is not stable).
PlayerBody script looks like this
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerBody : MonoBehaviour { public GameObject player; float clockwise = 50f; float counterClockwise = -50f;
void LateUpdate() { transform.position = player.transform.position; } void Update() { if (Input.GetKey(KeyCode.E)) { transform.Rotate(0, Time.deltaTime * clockwise, 0); } else if (Input.GetKey(KeyCode.Q)) { transform.Rotate(0, Time.deltaTime * counterClockwise, 0); } } }
And this is the script for controlling the Player.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
float maxSpeed = 10f;
private Rigidbody rb;
protected Joystick joystick;
void Start()
{
rb = GetComponent<Rigidbody>();
joystick = FindObjectOfType<Joystick>();
}
void FixedUpdate()
{
var rigidbody = GetComponent<Rigidbody>();
Vector3 movement = new Vector3(joystick.Horizontal * 40f, 0.0f, joystick.Vertical * 40f);
rb.AddForce(movement);
if (rb.velocity.magnitude > maxSpeed)
rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
}
}
Your answer
