How to make an object move in the direction another object is facing on 2 axis?
Basically, I'm trying to make a 3rd person game, where the forward button (w) will make the character move in the direction the camera is facing, and the backward button (s) to move in the other direction. This means you will turn by moving the camera. In the code, I have this working to an extent: I declared the variable public int distance = 2;
void Update () {
if(Input.GetKey("w")){
transform.position = transform.position + Camera.main.transform.forward * distance * Time.deltaTime;
}
if(Input.GetKey("s")){
transform.position = transform.position - Camera.main.transform.forward * distance * Time.deltaTime;
}
}
This would work, except it moves on all 3 axis (xyz), so if the camera is facing down slightly, it will try to walking into the ground, slowing it down, and sometimes going through the ground on parts of the map, so I just need it to move on the x and z axis. I can't freeze the y position, as I need it to fall sometimes, please help!
btw: sorry if this was hard to understand, I couldn't think how to word it
Answer by Positive7 · Sep 23, 2017 at 04:20 PM
private void Update()
{
var look = new Vector3(Camera.main.transform.forward.x, transform.position.y, Camera.main.transform.forward.z);
if (Input.GetKey("w"))
{
transform.position = transform.position + look * Distance * Time.deltaTime;
}
if (Input.GetKey("s"))
{
transform.position = transform.position - look * Distance * Time.deltaTime;
}
}
Thanks! This works great, apart from when I'm on some surfaces (such as a cube used as another floor for a house) it constantly hops (I haven't added code for jumping yet, so it can't be that), but then if I'm on another surface, such as a plane, it works perfectly. I may be able to change the scene so it works O$$anonymous$$, but is there anyway you could have a look?
i guess the jumping is caused because of the colliders on player and cube. or rigidbody. You can put a Physic material on the cube. or there are other fixes for this, but I'm from mobile now.
Ok, I've had a look, and it turns out It jumps a certain amount, due to it's global position. For example, if I move the whole map up just 1, the player jumps a huge amount way up into the sky, if I move the whole map down, the player shoots down loads too. I could just move it so that it works on that floor, but then it would be bad for other floors
Your answer
Follow this Question
Related Questions
transform.position is not updating the object's position 1 Answer
Need help with limited movement with mathf clamp 2 Answers
Rigidbody movement: Changing the Y of transform.position makes my character stutter 0 Answers
Move a object along a vector 1 Answer
Moving one gameobject to another being inconsistent. 0 Answers