- Home /
How to change addForce direction depending on camera direction
Hey so I was making a game where the player is almost the same where it is in the 'roll a ball tutorial' as it is a ball the rolls around when the player does WASD or arrow keys, I also added a script to the camera to make it orbit around the player when you move the mouse. But the trouble is that if I move my mouse & press W, instead of the ball rolling away from the camera, it rolls in the same direction as before. If possible I would prefer to keep it as the ball 'rolls' around rather than just translating is it has that 'inertia' & behaves just like a real ball would. Here is the code for the player movement:
public static float speed;
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);
}
& here is the code for the camera:
public GameObject player;
public Transform plyrTransform;
public Transform camTransform;
public Camera cam;
private float distance = 10.0f;
private float currentX = 0.0f;
private float currentY = 0.0f;
public float sensitivity = 1.0f;
private float sensitivityX = 0.0f;
private float sensitivityY = 0.0f;
void Start () {
camTransform = transform;
sensitivityX = sensitivity;
sensitivityY = sensitivity * 4;
}
void Update () {
currentX += Input.GetAxis ("Mouse X") * sensitivityX;
currentY += Input.GetAxis ("Mouse Y") * sensitivityY;
distance += Input.GetAxis ("Mouse ScrollWheel");
}
void LateUpdate () {
Vector3 dir = new Vector3 (0, 0, -distance);
Quaternion rotation = Quaternion.Euler (currentY, currentX, 0);
camTransform.position = plyrTransform.position + rotation * dir;
transform.LookAt (player.transform);
}
P.S, sorry if some of the code is unnecessary & messy, I am new to C# & follow a lot of tutorials.
Answer by hexagonius · Sep 30, 2018 at 08:08 PM
the movement code uses the axis as x and z input, which is in world space. to get a camera relative direction, use TransformDirection on the camera transform for that vector, save the magnitude, zero out y and set the saved magnitude again.
@hexagonius Thanks for the reply, but I am afraid I do not understand completely as I am new to C#
then you should try to learn C# first, as you will probably encounter your next problem right after this one is solved. and comment next time if you're not actually answering.
$$anonymous$$ thanx anyway, I think I can 'sort of' understand it I am just a bit confused about magnitude but I will search it up on the documentation.