For my Computer Science A-Level Programming Project I am developing a game and I wanted to include an acceleration and momentum system akin to the Genesis Sonic games. I have created an acceleration system however, for some reason it only allows my character to move left and not right. For obvious reasons I need it to move right.
Here is my code. It is written in C#:
float acceleration_speed = 0.46875f;
float deceleration_speed = 5.0f;
float friction_speed = 0.66875f;
float top_speed = 60.0f;
float horizontalMove = 0f;
if (Input.GetAxisRaw("Horizontal") < 0) //if player is pressing left
{
if (horizontalMove > 0.0f)
{
horizontalMove -= deceleration_speed; //decelerate
if (horizontalMove <= 0.0f)
{
horizontalMove = -0.5f;
}
}
else if (horizontalMove > -top_speed)
{
horizontalMove -= acceleration_speed; //accelerate
if (horizontalMove <= -top_speed)
{
horizontalMove = -top_speed; //impose top speed limit
}
}
}
if (Input.GetAxisRaw("Horizontal") > 0) //if player is pressing right
{
if (horizontalMove < 0.0f) //if moving to the left
{
horizontalMove += deceleration_speed; //decelerate
if (horizontalMove >= 0.0f)
{
horizontalMove = 0.5f;
}
else if (horizontalMove < top_speed)
{
horizontalMove += acceleration_speed; //accelerate
if (horizontalMove >= top_speed)
{
horizontalMove = top_speed; //impose top speed limit
}
}
}
}
if (Input.GetAxis("Horizontal") == 0)
{
horizontalMove -= friction_speed; //decelerate
if (horizontalMove <= 0)
{
horizontalMove = 0.0f;
}
}
I have used Input.GetAxisRaw to tell the program whether the player is moving left (-1) or right (1) or isn't moving at all (0).
I created the condition that if Input.GetAxisRaw < 0 (aka moving left) the system would accelerate the character in that direction, if Input.GetAxisRaw > 0 (aka moving right) the system would accelerate the character in that direction, if the character was already moving it would create friction to decelerate the character until it's speed is 0 and if the player character wasn't moving at all nothing would happen.
Now this code works when I hold the left input and do nothing but it doesn't work when I hold the right input as the player character doesn't even move.
Compare your code of the if (Input.GetAxisRaw("Horizontal") < 0) block with the if (Input.GetAxisRaw("Horizontal") > 0) block, you'll see you misplaced the else if block in the latter. Its inside of if (horizontalMove < 0.0f) { ... } thus it will never trigger if your character is not already moving left.
if (Input.GetAxisRaw("Horizontal") > 0) //if player is pressing right
{
if (horizontalMove < 0.0f) //if moving to the left
{
horizontalMove += deceleration_speed; //decelerate
if (horizontalMove >= 0.0f)
{
horizontalMove = 0.5f;
}
} // added
else if (horizontalMove < top_speed)
{
horizontalMove += acceleration_speed; //accelerate
if (horizontalMove >= top_speed)
{
horizontalMove = top_speed; //impose top speed limit
}
}
//} removed
}
You missing } in
if (Input.GetAxisRaw("Horizontal") > 0) //if player is pressing right
{
if (horizontalMove < 0.0f) //if moving to the left
{
horizontalMove += deceleration_speed; //decelerate
if (horizontalMove >= 0.0f)
{
horizontalMove = 0.5f;
}
//HERE YOU MISS }
else if (horizontalMove < top_speed)
{
horizontalMove += acceleration_speed; //accelerate
if (horizontalMove >= top_speed)
{
horizontalMove = top_speed; //impose top speed limit
}
}
}
}
I would suggest rewrite it so it could work with -1 and 1 input. Because you repeat the same code over again.
Related
I am making an endless runner mobile game. The PC controls work perfectly and the Touch/Swipe controls for Left and Right work too. The problem is when I swipe up to jump, the player jumps but then also either moves left or right (seemingly at random). For the life of me I cannot figure it out. This is my first C# project so my code/game is Frankenstein of tutorials and google searches. I found out about the rigidbody component a little too late but I don't want to start using it now if I don't have to... Please help, I am at a total loss. I would also like to apologise in advance if my code is extremely messy and incoherent, I have tried my best. Here is my Player movement script:
PC Controls
public class PlayerMove : MonoBehaviour
{
public float moveSpeed = 8;
public float leftRightSpeed = 7;
static public bool canMove = false;
public KeyCode moveL;
public KeyCode moveR;
public float horizVel = 0;
public int laneNum = 2;
public string controlLocked = "n";
private float speedUpTime;
private float waitTime = 0.45f;
private Vector3 startTouchPosition;
private Vector3 endTouchPosition;
public GroundCheck groundCheck;
public float jumpForce=7;
public float gravity = -9.81f;
public float gravityScale = 3;
public float jumpCoolDown = 0.5f;
private float lastJumpTime = 0;
float velocity;
// Start is called before the first frame update
void Start()
{
speedUpTime = Time.time;
}
// Update is called once per frame
void Update()
{
if (Time.time - speedUpTime >= 10f)
{
moveSpeed += 1;
leftRightSpeed +=1;
waitTime -= 0.05f;
speedUpTime = Time.time;
}
transform.position += new Vector3(horizVel, 0, moveSpeed) * Time.deltaTime;
if((Input.GetKeyDown(moveL)) && (laneNum>1)&& (controlLocked == "n"))
{
horizVel = -leftRightSpeed;
StartCoroutine(stopSlide());
laneNum -= 1;
controlLocked = "y";
}
if((Input.GetKeyDown(moveR)) && (laneNum<3)&& (controlLocked == "n"))
{
horizVel = leftRightSpeed;
StartCoroutine(stopSlide());
laneNum += 1;
controlLocked = "y";
}
velocity += gravity * gravityScale * Time.deltaTime;
if (groundCheck.isGrounded && velocity < 0)
{
velocity = 0;
lastJumpTime = 0;
}
if (Input.GetKeyDown(KeyCode.Space) && (Time.time - lastJumpTime) > jumpCoolDown)
{
lastJumpTime = Time.time;
velocity = jumpForce;
}
transform.Translate(new Vector3(0, velocity, 0) * Time.deltaTime);
Touch Controls
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
startTouchPosition = Input.GetTouch(0).position;
}
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
endTouchPosition = Input.GetTouch(0).position;
// Check for horizontal swipe
if((endTouchPosition.x < startTouchPosition.x) && (laneNum>1)&& (controlLocked == "n"))
{
horizVel = -leftRightSpeed;
StartCoroutine(stopSlide());
laneNum -= 1;
controlLocked = "y";
}
if((endTouchPosition.x > startTouchPosition.x) && (laneNum < 3) && (controlLocked == "n"))
{
horizVel = leftRightSpeed;
StartCoroutine(stopSlide());
laneNum += 1;
controlLocked = "y";
}
// Check for vertical swipe
if ((endTouchPosition.y > startTouchPosition.y) && (Time.time - lastJumpTime) > jumpCoolDown)
{
lastJumpTime = Time.time;
velocity = jumpForce;
}
}
}
IEnumerator stopSlide()
{
yield return new WaitForSeconds(waitTime);
horizVel = 0;
controlLocked = "n";
}
}
I've been at it for so many hours, I don't even remember what I've tried. Either the player stops moving, Right becomes Left, Jump is Right, Left is jump, etc...
Since you said the touch-controls were the issue, this answer will be focused on your second block of code.
The reason seems to be because when a player swipes up, their finger will almost never be at the same x-position. To illustrate this, try swiping up on your screen in an exact perfect line.
Computers take things very literally. So even being off by 0.0000001 is significant enough to be counted as less/more.
So what does this mean? When you swipe up, your fingers x and y position will change - causing both if-statements to activate
A fix that wouldn’t be too time-draining would be to create a dead-zone for swipes.
To put it simply, a dead-zone is a threshold that must be passed in addition to the action.
Here is an example of a dead-zone:
if(endPosition < startPosition - 2) { <SNIPPED> }
# ^ THIS IS THE DEADZONE
I'm working on a 2.5D player controller right now, and there is a problem with my dash in midair. The dash works, but the character can't be completely controlled on the X axis after the dash is finished until they hit the ground. I want the player to have full control on the X axis right after the dash so that they can dodge appropriately.
void Update()
{
PlayerInput();
}
void FixedUpdate()
{
xMovement();
yMovement();
}
void PlayerInput()
{
//Registers X and Y movement
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
if (Input.GetButton("Run"))
{
isRunning = true;
}
else if (Input.GetButtonUp("Run"))
{
isRunning = false;
}
//Makes player jump by returning a bool value to "yMovement()" when pressed.
if (Input.GetButtonDown("Jump"))
{
jumpRequest = true;
}
if (Input.GetKeyDown(KeyCode.A))
{
if (doubleTapTime > Time.time && lastKeyCode == KeyCode.A)
{
StartCoroutine(Dash(1f));
Debug.Log("You dashed left");
}
else
{
doubleTapTime = Time.time + 0.5f;
}
lastKeyCode = KeyCode.A;
}
if (Input.GetKeyDown(KeyCode.D))
{
if (doubleTapTime > Time.time && lastKeyCode == KeyCode.D)
{
StartCoroutine(Dash(-1f));
Debug.Log("You dashed right");
}
else
{
doubleTapTime = Time.time + 0.5f;
}
lastKeyCode = KeyCode.D;
}
}
void xMovement()
{
//Makes player walk left and right
if (!isRunning && !isDashing)
{
transform.Translate(Vector3.left * walkSpeed * horizontalInput * Time.deltaTime);
}
//Makes player run left and right
else if (isRunning && !isDashing)
{
transform.Translate(Vector3.left * runSpeed * horizontalInput * Time.deltaTime);
}
}
void yMovement()
{
//Make player jump when Jump is pressed
if (jumpRequest)
{
playerRb.velocity = new Vector3(playerRb.velocity.x, jumpForce);
jumpRequest = false;
//playerRb.velocity = new Vector2(playerRb.velocity.x, playerRb.velocity.y * jumpForce);
}
//Makes player fall faster in general, and when the Jump button is released
if (playerRb.velocity.y < 0)
{
playerRb.velocity += Vector3.up * Physics.gravity.y * (fallMultiplyer - 1) * Time.deltaTime;
}
else if (playerRb.velocity.y > 0 && !Input.GetButton("Jump"))
{
playerRb.velocity += Vector3.up * Physics.gravity.y * (lowJumpMultiplyer - 1) * Time.deltaTime;
}
}
IEnumerator Dash(float direction)
{
isDashing = true;
playerRb.velocity = new Vector3(playerRb.velocity.x, .0f);
playerRb.velocity = new Vector3(dashDistance * direction, 0f, 0f);
playerRb.useGravity = false;
yield return new WaitForSeconds(.2f);
isDashing = false;
playerRb.useGravity = true;
Any tips on code optimization is also greatly appreciated. I'm still fairly new to coding and would rather learn appropriate coding habits before I have to unlearn bad ones. Thank you!
I think your issue is that you're using a Translation on transform for the x axis when on the yAxis you're actually using the velocity. Unity might have trouble dealing with both in a single "FixedUpdate" call. Or it might just not do what you expect.
I would recommend sticking to velocity changes. So that would give something like
void xMovement()
{
//Makes player walk left and right
if (!isRunning && !isDashing)
{
playerRb.velocity += Vector3.left * walkSpeed * horizontalInput * Time.deltaTime;
}
//Makes player run left and right
else if (isRunning && !isDashing)
{
playerRb.velocity += Vector3.left * runSpeed * horizontalInput * Time.deltaTime;
}
}
I'll start this off by saying I am very new to Unity and C#, and I'm making my first solo project after following a tutorial series for Unity. I'm starting to make a first person shooter game, I have camera movement down, and I just wrote some code to handle player movement and acceleration. Initially when moving around a flat plane it works fine, but as soon as but as soon as my player object (PlayerColliderParent) bumps into a cube i have placed into the scene, it starts moving on its own at a constant speed and direction, depending on how it bumped into the cube. There aren't any other scripts that move PlayerColliderParent other than PlayerColliderParentScript.cs.
Here's a video of the problem occuring
why is it moving???
Here is PlayerColliderParentScript.cs (attached to PlayerColliderParent)
using System.Collections.Generic;
using UnityEngine;
public class PlayerColliderParentScript : MonoBehaviour
{
public Transform cameraRotation;
public Vector3 directionalInput;
public float accelerationFactor = 0.1f;
public float maxSpeed = 6f;
public Vector3 directionalSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//rotate horizontally with camera
transform.localEulerAngles = new Vector3(0, cameraRotation.localEulerAngles.y, 0);
}
void FixedUpdate()
{
//accelerate while movement key is held
//z axis
if (Input.GetKey(KeyCode.W))
{
directionalInput.z = 1;
if (directionalSpeed.z < maxSpeed)
{
directionalSpeed.z += accelerationFactor;
}
}
else if (Input.GetKey(KeyCode.S))
{
directionalInput.z = -1;
if (directionalSpeed.z < maxSpeed)
{
directionalSpeed.z += accelerationFactor;
}
}
else if (directionalSpeed.z > 0)
{
directionalInput.z = 0;
directionalSpeed.z -= accelerationFactor;
}
else if (directionalSpeed.z < 0)
{
directionalInput.z = 0;
directionalSpeed.z += accelerationFactor;
}
else
{
directionalInput.z = 0;
}
//x axis
if (Input.GetKey(KeyCode.D))
{
directionalInput.x = 1;
if (directionalSpeed.x < maxSpeed)
{
directionalSpeed.x += accelerationFactor;
}
}
else if (Input.GetKey(KeyCode.A))
{
directionalInput.x = -1;
if (directionalSpeed.x < maxSpeed)
{
directionalSpeed.x += accelerationFactor;
}
}
else if (directionalSpeed.x > 0)
{
directionalInput.x = 0;
directionalSpeed.x -= accelerationFactor;
}
else if (directionalSpeed.x < 0)
{
directionalInput.x = 0;
directionalSpeed.x += accelerationFactor;
}
else
{
directionalInput.x = 0;
}
//move the player according to directional speed
Vector3 direction = directionalInput.normalized * Time.deltaTime;
float velocityX = direction.x * directionalSpeed.x;
float velocityY = direction.y * directionalSpeed.y;
float velocityZ = direction.z * directionalSpeed.z;
Vector3 velocity = new Vector3(velocityX, velocityY, velocityZ);
transform.Translate(velocity);
}
}
Make sure to make the Rigidbody have isKinematic enabled. This way you can control it in FixedUpdate via the transform.Translate and it won't react to any Physics while the collision detection is still intact.
Otherwise in general whenever you have a Rigidbody you don't have want to set values via the Transform component.
I'm pretty sure what happens is that after you are already moving, the Rigidbody has a certain velocity. You are never again changing that velocity so after a collision you have both, the user Input applied via Transform and the Rigidbody's own velocity.
Instead of using transform.Translate rather directly manipulate the Rigidbody.velocity itself.
[SerializeField] Rigidbody _rigidbody;
...
//accelerate while movement key is held
//z axis
if (Input.GetKey(KeyCode.W))
{
directionalInput.z = 1;
directionalSpeed.z += accelerationFactor * Time.deltaTime;
}
else if (Input.GetKey(KeyCode.S))
{
directionalInput.z = -1;
directionalSpeed.z -= accelerationFactor * Time.deltaTime;
}
else
{
directionalInput.z = 0;
if (directionalSpeed.z > 0)
{
directionalSpeed.z -= accelerationFactor * Time.deltaTime;
}
else if (directionalSpeed.z < 0)
{
directionalSpeed.z += accelerationFactor * Time.deltaTime;
}
}
directionalSpeed.z = Mathf.Clamp(directionalSpeed.z, -maxSpeed, maxSpeed);
//x axis
if (Input.GetKey(KeyCode.D))
{
directionalInput.x = 1;
directionalSpeed.x += accelerationFactor * Time.deltaTime;
}
else if (Input.GetKey(KeyCode.A))
{
directionalInput.x = -1;
directionalSpeed.x -= accelerationFactor * Time.deltaTime;
}
else
{
directionalInput.x = 0;
if (directionalSpeed.x > 0)
{
directionalSpeed.x -= accelerationFactor * Time.deltaTime;
}
else if (directionalSpeed.x < 0)
{
directionalSpeed.x += accelerationFactor * Time.deltaTime;
}
}
directionalSpeed.x = Mathf.Clamp(directionalSpeed.x, -maxSpeed, maxSpeed);
_rigidbody.velocity = directionalInput;
As mentioned by #Rhach also the rotation is an issue.
You should probably rather use e.g.
_rigidbody.MoveRotation(new Vector3(0, cameraRotation.localEulerAngles.y, 0));
I'll start off by saying I'm very new to Unity and C# and I'm attempting my first project after following a series of youtube tutorials. I manually made physics for my player (for acceleration, airborne velocity and drag, gravity, etc), but when I jump moving forward (or any other direction for that matter), when I rotate my character (through my mouse movement) my airborne movement changes relative to my rotation rather than remaining constant (I guess since it's moving in local space?). I'd like it so my airborne velocity gets influenced by my grounded velocity (that which is influenced by WASD), but doesn't move relative to my rotation, and i keep my movement direction no matter where I look.
I've been pouring overt my code for a while but I can't figure it out.
My player is called PlayerColliderParent, it has a Character Controller attached to it, along with my script PlayerColliderParentScript.cs (which handles all physics and movement for the player).
TLDR or if that was too confusing: When my player is airborne and moving, the direction of movement changes along with the player's rotation (where I look). I'd rather the direction remained constant regardless of the rotation.
Any help is appreciated as I really want to fix this.
Here is a video of the problem occuring: https://www.youtube.com/watch?v=wpEMv059cZs
And here is PlayerColliderParentScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerColliderParentScript : MonoBehaviour
{
public Transform cameraRotation;
public Vector3 directionalInput;
public float accelerationAmount = 0.5f;
public float maxSpeed = 6f;
public float maxMoveSpeed =6f;
public Vector3 directionalSpeed;
public Vector3 airDirectionalSpeed;
public float terminalVelocity = 30f;
public float gravityStrength = 1f;
public float currentYvel;
public float airDrag;
public float maxAirSpeed;
public float jumpStrength = 1f;
Vector3 gravityController;
//Rigidbody playerBody = new Rigidbody();
CharacterController controller = new CharacterController();
//Rigidbody playerBody = new Rigidbody();
// Start is called before the first frame update
void Start()
{
//playerBody = GetComponent<Rigidbody>();
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
//set acceleration factor
float accelerationFactor = (accelerationAmount * 200) * Time.deltaTime;
//rotate horizontally with camera
transform.localEulerAngles = new Vector3(0, cameraRotation.localEulerAngles.y, 0);
//JUMP or press against ground
if (controller.isGrounded == true)
{
if (Input.GetKey(KeyCode.Space))
{
currentYvel = jumpStrength;
}
else
{
currentYvel = -2f /** Time.deltaTime * 500*/;
}
}
//accelerate while movement key is held
//z axis
if (Input.GetKey(KeyCode.W))
{
directionalInput.z = 1;
if (directionalSpeed.z < maxSpeed)
{
directionalSpeed.z += accelerationFactor;
}
}
else if (Input.GetKey(KeyCode.S))
{
directionalInput.z = -1;
if (directionalSpeed.z < maxSpeed)
{
directionalSpeed.z += accelerationFactor;
}
}
else if (directionalSpeed.z > 0)
{
if (controller.isGrounded == true)
{
directionalInput.z = 0;
directionalSpeed.z -= accelerationFactor;
}
else
{
directionalSpeed.z -= airDrag * Time.deltaTime * 100;
}
}
else if (directionalSpeed.z < 0)
{
if (controller.isGrounded == true)
{
directionalInput.z = 0;
directionalSpeed.z += accelerationFactor;
}
else
{
directionalSpeed.z += airDrag * Time.deltaTime * 100;
}
}
else
{
directionalInput.z = 0;
}
//x axis
if (Input.GetKey(KeyCode.D))
{
directionalInput.x = 1;
if (directionalSpeed.x < maxSpeed)
{
directionalSpeed.x += accelerationFactor;
}
}
else if (Input.GetKey(KeyCode.A))
{
directionalInput.x = -1;
if (directionalSpeed.x < maxSpeed)
{
directionalSpeed.x += accelerationFactor;
}
}
else if (directionalSpeed.x > 0)
{
if (controller.isGrounded == true)
{
directionalInput.x = 0;
directionalSpeed.x -= accelerationFactor;
}
else
{
directionalSpeed.x -= airDrag * Time.deltaTime * 100;
}
}
else if (directionalSpeed.x < 0)
{
if (controller.isGrounded == true)
{
directionalInput.x = 0;
directionalSpeed.x += accelerationFactor;
}
else
{
directionalSpeed.x += airDrag * Time.deltaTime * 100;
}
}
else
{
directionalInput.x = 0;
}
//accelerate downwards if not grounded
if (controller.isGrounded == false)
{
if (currentYvel > -terminalVelocity)
{
currentYvel -= gravityStrength * Time.deltaTime;
}
}
//Reset gravity vecctor
gravityController = Vector3.zero;
//calculate movement velocity
Vector3 direction = directionalInput.normalized;
float velocityX = direction.x * Mathf.Round(directionalSpeed.x);
float velocityY = (currentYvel / 2) * Time.deltaTime;
float velocityZ = direction.z * Mathf.Round(directionalSpeed.z);
Vector3 velocity = new Vector3(velocityX * Time.deltaTime, velocityY, velocityZ * Time.deltaTime);
//check for sprint key
if (Input.GetKey(KeyCode.LeftShift))
{
velocity *= 1.5f;
}
//move player according to velocity
controller.Move(transform.TransformDirection(velocity));
//set airspeed the same as character velocity
airDirectionalSpeed.x = velocityX * Time.deltaTime;
airDirectionalSpeed.y = 0;
airDirectionalSpeed.z = velocityZ * Time.deltaTime;
if (airDirectionalSpeed.x > 0)
{
airDirectionalSpeed.x -= airDrag * Time.deltaTime * 100;
}
if (airDirectionalSpeed.z > 0)
{
airDirectionalSpeed.z -= airDrag * Time.deltaTime * 100;
}
airDirectionalSpeed = transform.TransformDirection(airDirectionalSpeed);
Vector3 airVelocity = new Vector3(airDirectionalSpeed.x, 0, airDirectionalSpeed.z);
Vector3 airMoveAmountX = new Vector3((airVelocity.x / 3), 0, 0);
Vector3 airMoveAmountZ = new Vector3(0, 0, (airVelocity.z / 3));
//move player according to airspeed
if (controller.isGrounded == false)
{
if (airDirectionalSpeed.x < maxAirSpeed | airDirectionalSpeed.x > -maxAirSpeed)
{
controller.Move(airMoveAmountX);
}
if (airDirectionalSpeed.z < maxAirSpeed | airDirectionalSpeed.z > -maxAirSpeed)
{
controller.Move(airMoveAmountZ);
}
}
}
}
This part smells:
void Update()
{
// (...)
if (Input.GetKey(KeyCode.D))
{
directionalInput.x = 1;
if (directionalSpeed.x < maxSpeed)
{
directionalSpeed.x += accelerationFactor;
}
}
//(...)
}
If your are not grounded, you shouldn't be responding to directional inputs and accelerating in horizontal direction. Same applies for the corresponding logic for the other 3 directional keys.
You can try to add a condition to only execute this logic if the player is grounded.
Having a bit of a problem in Unity3D. I have a fly camera with both a box collider and rigidbody, and it still moves through my terrain, which has a terrain collider and a rigidbody. The thing is, it interacts with my capsules just fine, bounces them away and everything. Obvious this is the exact opposite of what I want ha ha...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlyCamera : MonoBehaviour
{.
/*
Writen by Windexglow 11-13-10. Use it, edit it, steal it I don't care.
Converted to C# 27-02-13 - no credit wanted.
Simple flycam I made, since I couldn't find any others made public.
Made simple to use (drag and drop, done) for regular keyboard layout
wasd : basic movement
shift : Makes camera accelerate
space : Moves camera on X and Z axis only. So camera doesn't gain any height*/
float mainSpeed = 25.0f; //regular speed
float shiftAdd = 250.0f; //multiplied by how long shift is held. Basically running
float maxShift = 1000.0f; //Maximum speed when holdin gshift
float camSens = 0.25f; //How sensitive it with mouse
private Vector3 lastMouse = new Vector3(255, 255, 255); //kind of in the middle of the screen, rather than at the top (play)
private float totalRun = 1.0f;
void Update()
{
if (Input.GetKey(KeyCode.R))
{
transform.position = new Vector3(26f, 4f, 14f);
}
lastMouse = Input.mousePosition - lastMouse;
lastMouse = new Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0);
lastMouse = new Vector3(transform.eulerAngles.x + lastMouse.x, transform.eulerAngles.y + lastMouse.y, 0);
transform.eulerAngles = lastMouse;
lastMouse = Input.mousePosition;
//Mouse camera angle done.
//Keyboard commands
float f = 0.0f;
Vector3 p = GetBaseInput();
if (Input.GetKey(KeyCode.LeftShift))
{
totalRun += Time.deltaTime;
p = p * totalRun * shiftAdd;
p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
}
else
{
totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
p = p * mainSpeed;
}
p = p * Time.deltaTime;
Vector3 newPosition = transform.position;
if (Input.GetKey(KeyCode.Space))
{ //If player wants to move on X and Z axis only
transform.Translate(p);
newPosition.x = transform.position.x;
newPosition.z = transform.position.z;
transform.position = newPosition;
}
else
{
transform.Translate(p);
}
}
private Vector3 GetBaseInput()
{ //returns the basic values, if it's 0 than it's not active.
Vector3 p_Velocity = new Vector3();
if (Input.GetKey(KeyCode.W))
{
if (transform.position.x > 2 && transform.position.x < 53)
{
if (transform.position.y > 0 && transform.position.y < 40)
{
if (transform.position.z > 5 && transform.position.z < 52)
{
p_Velocity += new Vector3(0, 0, 1);
}
}
}
}
if (Input.GetKey(KeyCode.S))
{
if (transform.position.x > 2 && transform.position.x < 53)
{
if (transform.position.y > 0 && transform.position.y < 40)
{
if (transform.position.z > 5 && transform.position.z < 52)
{
p_Velocity += new Vector3(0, 0, -1);
}
}
}
}
if (Input.GetKey(KeyCode.A))
{
if (transform.position.x > 2 && transform.position.x < 53)
{
if (transform.position.y > 0 && transform.position.y < 40)
{
if (transform.position.z > 5 && transform.position.z < 52)
{
p_Velocity += new Vector3(-1, 0, 0);
}
}
}
}
if (Input.GetKey(KeyCode.D))
{
if (transform.position.x > 2 && transform.position.x < 53)
{
if (transform.position.y > 0 && transform.position.y < 40)
{
if (transform.position.z > 5 && transform.position.z < 52)
{
p_Velocity += new Vector3(1, 0, 0);
}
}
}
}
return p_Velocity;
}
}
This flycam isn't mine so if it's not optimal for the use I'm looking for, please notify me about that too.
Basically you are. Transforming it not adding velocity thats why it is crossing the collider
You need to get reference of the rigidbody then add velocity to it
Then it won't cross the collider
You need to modify your code for that
Where you are transforming
Instead of transforming
You need to
Rigidbody.velocity= vector3(.....)
Never mind, I fixed the problem.
I ended up having Kinematic ticked on the box collider of the camera, so that must have messed it up.