Question by
TheFuzzyketchup · Oct 26, 2015 at 06:45 PM ·
c#camerarotation
Roll a ball, treating where the camera is rotating as forward?
First thing I want to say is I'm pretty new to Unity, and programming in C#. With that in mind...
I've got a simple project set up where I can roll a ball, and rotate the camera around the ball, but I can't figure out how to make the ball think that the camera is facing forward. The only solution that's worked at all is
Vector3 direction = MainCamera.transform.forward;
direction.y = 0;
direction.x = 0;
direction.Normalize();
player.transform.Translate(direction * Time.deltaTime * sensativityType, Space.World);
The problem here is that it moves the ball without an AddForce in the rigidbody being used.
Here is my code so far
Player Controller:
public float speed;
public Camera mainCamera;
public GameObject player;
public int jumpSpeed;
private Vector3 movement;
private Vector3 jumping;
private Rigidbody rb;
private float moveHorizontal;
private float moveVertical;
private float moveJump;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate() //FixedUpdate is called before any physics are applied
{
moveHorizontal = Input.GetAxis("Horizontal");
moveVertical = Input.GetAxis("Vertical");
moveJump = Input.GetAxis("Jump");
//Phone support code that isn't being accessed goes here
movement = new Vector3(moveHorizontal, 0f, moveVertical);
rb.AddForce(movement * speed);
}
Camera Controller:
public GameObject player; public Rigidbody rb; public int sensativity; public int mobileSensativity; public float distance;
private Quaternion q;
private int sensativityType;
private Vector3 offset;
private Vector3 reset;
private Quaternion defaultRotate;
private Vector2 touchOrigin = -Vector2.one;
private Vector2 touchEnd;
public Camera MainCamera;
// Use this for initialization
void Start () {
reset = new Vector3(0, 0.5f, 0);
offset = (transform.position - player.transform.position).normalized * distance;
}
// LastUpdate is called once per frame after the main Update() function
void LateUpdate () {
if (Screen.currentResolution.width > Screen.currentResolution.height)
{
MainCamera.aspect = (Screen.currentResolution.width / Screen.currentResolution.height);
} else
{
MainCamera.aspect = (Screen.currentResolution.height / Screen.currentResolution.width);
}
transform.position = player.transform.position + offset;
if (player.transform.position.y <= -10)
{
rb.isKinematic = true;
player.transform.position = reset;
rb.isKinematic = false;
}
q = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * sensativity, Vector3.up);
offset = q * offset;
sensativityType = sensativity;
transform.position = player.transform.position + offset;
transform.LookAt(player.transform.position);
Vector3 direction = MainCamera.transform.forward;
direction.y = 0;
direction.x = 0;
direction.Normalize();
player.transform.Translate(direction * Time.deltaTime * sensativityType, Space.World);
}
Comment