- Home /
How to keep player from going below the floor?
Hey, so I created a script for a first person game easy enough, and it basically moved the player whenever they pressed the move keys. However, I wanted it so that it would move wherever the player was looking. But, I don't want the player's y axis. And since my current code takes in x, y, and z, it's letting me move through the floor and all that bad stuff. Here's my code for the movement of the player:
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public float speed = 6f;
Vector3 movement;
Rigidbody playerRigidbody;
int floorMask;
float camRayLength = 100f;
private void Awake() {
floorMask = LayerMask.GetMask("Floor");
playerRigidbody = GetComponent<Rigidbody>();
}
private void FixedUpdate() {
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D)) {
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Move(horizontal, vertical);
}
}
private void Move(float horizontal, float vertical) {
movement.Set(horizontal, 0f, vertical);
// Normalize speed so they don't go faster by going diagonally
// movement = movement.normalized * speed * Time.deltaTime;
transform.position += transform.forward * Time.deltaTime * speed;
playerRigidbody.MovePosition(transform.position + movement);
}
}
In summary of this code, it basically fires Move()
when the player pressed ASWD (if it didn't, it would constantly move the player where they were looking, just because of how this is set up). So, firstly, any suggestions, and secondly, how can I keep the y from changing?
To clarify, is the issue that your character is falling through a totally flat floor, or that you have inclines and declines and your character is walking through those?
@NonsenseSynapse It's neither. The player isn't falling through the floor, but it is able to, because the y changes depending on the mouse location.
Why do you have a “vertical” float if you don’t want the player to move along the y-axis?
Answer by MechaWolf99 · Apr 17, 2018 at 02:11 PM
I can't say for sure. But could do two things. One, if the player will always be at the same height, then make a new vector3 and set it's x, and z to be the same as transfrom.position, and set y to the level of the floor. The other option that I can think of is to make a new vector3, set it to be the same x,y,z of transfrom.position. But for y, subtract the new position form it. Then of course set transfrom.position to be the vector3. Hope this helps. If not then I can try to write some code up for you.
Your answer
Follow this Question
Related Questions
Vertical & horizontal movement world axis (top view) 1 Answer
how to stop something from following in the y axis 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Camera Movement 0 Answers
Need help with WASD plus mouselook movement,,Need help with WASD movement 0 Answers