Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

FPS Player Movement Script in Unity. I am following the FPS Tutorials for writing my first 'First Person Shooter' game in Unity. The tutorial I

FPS Player Movement Script in Unity. I am following the "FPS Tutorials" for writing my first 'First Person Shooter' game in Unity. The tutorial I am following is written in Javascript, and I have been translating into C# with only C++ knowledge, all while never using Unity before. Overall, I have it working. Here is the issue: the player moves around, jumps, crouches, etc. The problem is when the player "looks around", it throws off the directional reference points. In other words, if the player looks right, you have to use the right arrow to move forward, the left arrow to move backward, the forward arrow to move right, and the back arrow to move left. I thought I had a line in there to make the forward y-direction always be "forward". Please help me figure out how I can ALWAYS use forward for forward, backward for backward, right for right and left for left, no matter which direction the player is facing! Here is my code, and I apologize ahead of time for the excessive comments, its how I learn. Player Movement Script:

using UnityEngine;

[RequireComponent(typeof(Rigidbody))] public class PlayerMovement : MonoBehaviour { public float walkAcceleration = 5; public float walkAccelAirRatio = 0.1f; public float walkDeacceleration = 5; [HideInInspector] public float walkDeaccelerationVelx; [HideInInspector] public float walkDeaccelerationVelz; public GameObject cameraObject; public float maxWalkSpeed = 20; private Rigidbody rB; [HideInInspector] public Vector2 horizontalMovement; public float jumpVelocity = 20; [HideInInspector] public bool grounded = false; public float maxSlope = 60; public float crouchRatio = 0.3f; public float transToCrouchSec = 0.2f; public float crouchingVelocity; public float currentCrouchRatio = 1; public float originalLocalScaleY; public float crouchLocalScaleY; public GameObject collisionDetectionSphere;

void Awake() { currentCrouchRatio = 1; // Initializing Crouch Ratio to 1 originalLocalScaleY = transform.localScale.y; // Setting Parameter Equal to Its Object crouchLocalScaleY = transform.localScale.y * crouchRatio; // Formula for Crouch Scale }

// Use This For Initialization // Start Is Called Before the First Frame Update void Start() { rB = GetComponent(); // Parameter "rB" Initialized to Rigidbody Component in Unity }

// Update Is Called Once Per Frame void FixedUpdate() { Vector3 temp2 = transform.localScale; // Creating a Temporary Variable to Allow Modification of Members temp2.y = Mathf.Lerp(crouchLocalScaleY, originalLocalScaleY, currentCrouchRatio); // Assigning Temporary Variable to Local Scale transform.localScale = temp2; // Driving Home That They Are Equal

if (Input.GetButton("Crouch")) // If 'c' is Pressed, Crouch! currentCrouchRatio = Mathf.SmoothDamp(currentCrouchRatio, 0, ref crouchingVelocity, transToCrouchSec);

// If 'c' is Not Pressed, Don't Crouch, and Detect Any Collisions Above Player's Head. If Not, Stand Up... if (Input.GetButton("Crouch") == false && collisionDetectionSphere.GetComponent().collisionDetected == false) currentCrouchRatio = Mathf.SmoothDamp(currentCrouchRatio, 1, ref crouchingVelocity, transToCrouchSec);

horizontalMovement = new Vector2(rB.velocity.x, rB.velocity.z); // Store The X & Z-Components of Velocity Into the 2 Element Vector

if (horizontalMovement.magnitude > maxWalkSpeed) // If Walk Speed Is Greater Than "maxWalkSpeed"... { horizontalMovement = horizontalMovement.normalized; // Make "horizontalMovement" Magnitude Equal to 1 horizontalMovement *= maxWalkSpeed; // Multiply "maxWalkSpeed" By This Normalized 2D Vector Over and Over // Continue Until Horizontal Movement Equals "maxWalkSpeed" }

Vector3 temp1 = rB.velocity; // Creating a Temporary Variable to Allow Modification of Members temp1.x = horizontalMovement.x; // Assigning Temporary Variables to Horizontal Movement in X-Direction temp1.z = horizontalMovement.y; // Assigning Temporary Variables to Horizontal Movement in Y-Direction rB.velocity = temp1; // Driving Home That They Are Equal

// If User's Feet Are On The Ground, Or If Isn't Hitting the Directional Arrows // Or If User Changes Directions... if (grounded) { temp1.x = Mathf.SmoothDamp(temp1.x, 0, ref walkDeaccelerationVelx, walkDeacceleration); // ...Slow Down X-Direction Gradually temp1.z = Mathf.SmoothDamp(temp1.z, 0, ref walkDeaccelerationVelz, walkDeacceleration); // ...Slow Down Z-Direction Gradually }

// Prevent Rotation Around the X & Z-axes // Make the Y-Axis "Point Forward" In the Main Camera (Matched to PlayerCapsule) ***This is the Line I thought I Needed*** transform.rotation = Quaternion.Euler(0, cameraObject.GetComponent().currentYRotation, 0);

if (grounded) // If the Player's Feet Are On The Ground... { /// ...Add a Constant Relative Force With the Pressing of the Arrow Keys rB.AddRelativeForce(Input.GetAxisRaw("Horizontal") * walkAcceleration * Time.deltaTime, 0, Input.GetAxisRaw("Vertical") * walkAcceleration * Time.deltaTime); }

else // Add Limited Air Control So User Can "Land" With Some Accuracy { rB.AddRelativeForce(Input.GetAxisRaw("Horizontal") * walkAcceleration * walkAccelAirRatio * Time.deltaTime, 0, Input.GetAxisRaw("Vertical") * walkAcceleration * walkAccelAirRatio * Time.deltaTime); }

if (Input.GetButtonDown("Jump") && grounded) // If the Jump Button Set In Inputs is Pressed, Not Held... { rB.AddForce(0, jumpVelocity, 0); // ...Add Jump Velocity to Player } }

// Anytime the Sphere Comes in Contact With Another Collider... void OnCollisionStay(Collision collision) // Save the Info in a Variable Named "collision" of "Collision" Datatype { foreach(ContactPoint contact in collision.contacts) // For Each Collision Detected... { if(Vector3.Angle(contact.normal, Vector3.up) < maxSlope) // If the Object Collided With Has A Slope Greater Than 60 Degrees... { grounded = true; // ...Do Not Allow the Player to Jump (Off of Object) } } }

void OnCollisionExit(Collision collision) // Not Allowing User to Jump Until After Previous Jump Action Finishes Execution { grounded = false; // Wait Until Finished } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Transactions On Large Scale Data And Knowledge Centered Systems X Special Issue On Database And Expert Systems Applications Lncs 8220

Authors: Abdelkader Hameurlain ,Josef Kung ,Roland Wagner ,Stephen W. Liddle ,Klaus-Dieter Schewe ,Xiaofang Zhou

2013th Edition

3642412203, 978-3642412202

More Books

Students also viewed these Databases questions

Question

Show 2(3+log23)n-2 2(3n-2)3m

Answered: 1 week ago

Question

4. Explain the strengths and weaknesses of each approach.

Answered: 1 week ago

Question

3. Identify the methods used within each of the three approaches.

Answered: 1 week ago