- Home /
Moving towards where the camera is looking
I'm trying to make a "marble blast" style game, where you control a ball.
I currently have a camera that orbits around a ball, and the camera is controlled by the mouse. I added basic movement to the ball using addforce, but now I'm trying to modify my script so that when you press W (or forward on the stick) you move forward in the direction the camera is facing, and if you press right, the ball moves to the right of the camera etc. etc.
I'm having issues modifying my code to do this and move relative to where the camera is facing. Any help is greatly appreciated!
I have looked through similar threads, but all of them use translation for the character, and I can't seem to figure it out for adding physics forces in the camera's direction.
Below is the code I'm trying to modify:
using UnityEngine;
using System.Collections;
public class s_PlayerMovement : MonoBehaviour {
public float speed;
public Camera datCamera;
private Rigidbody rb;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
}
}
Hi, I don't have time to test my answer but I think you can try somethings like :
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 h$$anonymous$$ovement = moveHorizontal * datCamera.transform.right;
Vector3 v$$anonymous$$ovement = moveVertical * datCamera.transform.forward;
rb.AddForce ((h$$anonymous$$ovement + v$$anonymous$$ovement) * speed);
If that doesn't works the key point for your search is :
"datCamera.transform.forward" and "datCamera.transform.right" which are the camera forward vector and right vector.
I hope this is helpfull....
It works perfectly! Thank you so much :D
Looking at the code, it makes perfect sense, I just couldn't for the life of me figure that out.