- Home /
FPS Controller with relative X/Z movement
I'm making a game where the player can walk on walls. I'm trying to achieve this by making the player a child to whichever wall he/she is walking on. This way, all rotation, gravity and movement of the player assumes that the wall is actually the floor.
I'm using this modified FPS script:
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (Rigidbody))]
[RequireComponent (typeof (CapsuleCollider))]
public class FPSController : MonoBehaviour {
public float speed = 10.0f;
public float gravity = 10.0f;
public float maxVelocityChange = 10.0f;
public bool canJump = true;
public float jumpHeight = 2.0f;
public bool grounded = false;
void Awake () {
rigidbody.freezeRotation = true;
rigidbody.useGravity = false;
}
void FixedUpdate () {
if (grounded) {
// Calculate how fast we should be moving
Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
targetVelocity = transform.TransformDirection(targetVelocity);
targetVelocity *= speed;
// Apply a force that attempts to reach our target velocity
Vector3 velocity = rigidbody.velocity;
Vector3 velocityChange = (targetVelocity - velocity);
velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
}
// We apply gravity manually for more tuning control
//rigidbody.AddForce((this.transform.up * -gravity * rigidbody.mass));
this.rigidbody.AddForce(-this.transform.up * 9.8f);
grounded = false;
}
void OnCollisionStay () {
grounded = true;
}
float CalculateJumpVerticalSpeed () {
// From the jump height and gravity we deduce the upwards speed
// for the character to reach at the apex.
return Mathf.Sqrt(2 * jumpHeight * gravity);
}
}
The problem I'm having is that the script doesn't move the X and Z position of the player relative to the parent wall. If I try to move forward on a wall, nothing happens because the script views it as the Y axis, even though it's the player's relative Z.
How could I modify this so that the X and Z movement are relative?
Your answer
![](https://koobas.hobune.stream/wayback/20220613131713im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to use lookAt() while my character walking on a wall ? 0 Answers
Help with Colliders? 0 Answers
How to simulate bullet penetrating a cube? 1 Answer
how to make CharacterCollider ignore LayerMask? 1 Answer
Gun goes through walls (FPS) 1 Answer