Continue moving in the same direction as the last input - c#

I am working on my spaceship game. I have done a lot of things in it but now I am facing a problem. The controls of the game are made by Input.GetAxis.
What I want to do now is that once I take the thinger of the W key, for the player to continue move in the same direction or from others keys. I want the player to continue moving in the same direction as the last input and if the gamer will want to change its direction he will need to click on another button, and then it will start moving in another direction. I tried it by myself but I didn't succeed.
public float Force;
public Rigidbody rb;
public float speed;
public Done_Boundary boundary;
public float RotSpeed;
public GameObject shot;
public Transform shotSpawn;
public float fireRate;
private float nextFire;
/*public Text bullettext;
public int maxbullet = 35;
public int curbullet = 0;
public GameObject NoBulletP;
public bool bulletgiving = false;
public void OK()
{
NoBulletP.SetActive (false);
}*/
void Start()
{
//curbullet = maxbullet;
rb = GetComponent<Rigidbody> ();
}
void Update ()
{
//bullettext.text = "Bullets: " + curbullet;
if (Input.GetButton ("Fire1") && Time.time > nextFire)
{
/*if (curbullet == 0)
{
NoBulletP.SetActive (true);
if(!bulletgiving)
{
StartCoroutine (wait());
}
}
else if(curbullet > 0)
{
curbullet--;*/
Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
nextFire = Time.time + fireRate;
GetComponent<AudioSource> ().Play ();
/*}
else if(curbullet < 0)
{
curbullet = 0;
}*/
}
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
rb.velocity = transform.forward * moveVertical * speed;
transform.Rotate (0.0f,moveHorizontal * RotSpeed * Time.deltaTime,0.0f);
rb.position = new Vector3(Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax));
}

That's happening because Input.GetAxis("Horizontal") and Input.GetAxis("Vertical") gets a value of 0 when the key is not being pressed.
Change the the code in FixedUpdate() to this:
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = 0f;
if (Input.GetAxisRaw("Vertical") != 0f)
{
moveVertical = Input.GetAxisRaw("Vertical");
rb.velocity = transform.forward * moveVertical * speed;
}
transform.Rotate(0.0f, moveHorizontal * RotSpeed * Time.deltaTime, 0.0f);
rb.position = new Vector3(Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp(rb.position.z, boundary.zMin, boundary.zMax));
rb.AddForce(transform.forward * Force);
}
I'm using GetAxisRaw because it gives a value of -1 or 1 when is pressed and 0 when its not.

Related

How do I make it so that the Rotation of the player object does not affect the Input.GetAxisRaw("Horizonatal")?

In my code, when I change the rotation of the player object, the Input.GetAxisRaw("Horizontal") also follows that rotation and messes the whole player controller up. How do I make it so that the Input.GetAxis is permanent and stays in place? The whole rotation is being done in the if statement of if Input.GetKey("a").
using UnityEngine;
public class JUSTMOVE : MonoBehaviour
{
public float speed = 7f;
Vector3 moveDirection;
public Rigidbody rb;
float horizontalMovement;
float verticalMovement;
public float movementMultiplier = 10f;
bool grounded;
public float groundDrag = 6;
public LayerMask whatIsGround;
public float airMultiplier = 3f;
public float playerHeight = 2f;
public float jumpForce = 5f;
void FixedUpdate()
{
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);
horizontalMovement = Input.GetAxisRaw("Horizontal");
if (grounded)
rb.drag = groundDrag;
else
rb.drag = 0;
moveDirection = transform.forward * verticalMovement + transform.right * horizontalMovement;
if(grounded)
{
rb.AddForce(moveDirection.normalized * speed * movementMultiplier, ForceMode.Force);
} else if(!grounded)
{
rb.AddForce(moveDirection.normalized * speed * movementMultiplier * airMultiplier, ForceMode.Force);
}
if(Input.GetKey("a"))
{
transform.localRotation = Quaternion.Euler(0,270,0);
}
Vector3 flatVel = new Vector3(rb.velocity.x, 0f,rb.velocity.z);
if(flatVel.magnitude > speed)
{
Vector3 limitedVel = flatVel.normalized * speed;
rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
}
if(Input.GetKey("w") && grounded)
{
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}
}
}
If I get it right, you want a top/down controller instead of a first/third person controller ?
If so, you need to move align the camera rotation instead of you character rotation.
Replace this :
moveDirection = transform.forward * verticalMovement + transform.right * horizontalMovement;
By this :
moveDirection = Camera.main.transform.forward * verticalMovement + Camera.main.transform.right * horizontalMovement;

How to jump properly using character controller?

I'm using a character controller for my player movement. I had walking and running working, but I couldn't get the jumping to work.
Here is my code:
[SerializeField] Transform playerCamera = null;
[SerializeField] float mouseSensitivity = 3.5f;
[SerializeField] float walkSpeed = 10.0f;
[SerializeField] float RunSpeed = 12.0f;
[SerializeField] float gravity = 9.81f;
[SerializeField] bool lockCursor = true;
[SerializeField] [Range(0.0f, 0.5f)] float moveSmoothTime = 0.3f;
[SerializeField] [Range(0.0f, 0.5f)] float mouseSmoothTime = 0.03f;
public float jumpHeight = 3f;
Vector3 velocity;
public float verticalVelocity;
float cameraPitch = 0.0f;
float VelocityY = 0.0f;
CharacterController controller = null;
Vector2 currentDir = Vector2.zero;
Vector2 currentDirVelocity = Vector2.zero;
Vector2 currentMouseDelta = Vector2.zero;
Vector2 currentMouseDeltaVelocity = Vector2.zero;
void Start()
{
controller = GetComponent<CharacterController>();
if (lockCursor)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
void Update()
{
UpdateMouseLook();
UpdateMovement();
}
void UpdateMouseLook()
{
Vector2 targetMouseDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
currentMouseDelta = Vector2.SmoothDamp(currentMouseDelta, targetMouseDelta, ref currentMouseDeltaVelocity, mouseSmoothTime);
cameraPitch -= currentMouseDelta.y * mouseSensitivity;
cameraPitch = Mathf.Clamp(cameraPitch, -90.0f, 90.0f);
playerCamera.localEulerAngles = Vector3.right * cameraPitch;
transform.Rotate(Vector3.up * currentMouseDelta.x * mouseSensitivity);
}
void UpdateMovement()
{
Vector2 targetDir = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
targetDir.Normalize();
currentDir = Vector2.SmoothDamp(currentDir, targetDir, ref currentDirVelocity, moveSmoothTime);
if (controller.isGrounded)
VelocityY = 0.0f;
VelocityY += gravity * Time.deltaTime;
velocity = (transform.forward * currentDir.y + transform.right * currentDir.x) * walkSpeed + Vector3.up * VelocityY;
controller.Move(velocity * Time.deltaTime);
if ((Input.GetKey("left shift") || Input.GetKey("right shift")) && controller.isGrounded && !Input.GetKey(KeyCode.S) && !Input.GetKey(KeyCode.DownArrow))
{
velocity = (transform.forward * currentDir.y + transform.right * currentDir.x) * RunSpeed + Vector3.up * VelocityY;
controller.Move(velocity * Time.deltaTime);
}
if (Input.GetKeyDown(KeyCode.J) && controller.isGrounded)
{
Debug.Log("Now Jumping!!");
VelocityY = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
}
Note: I'm not using rigidbody on my character.
The jumping is not working every time, on some clicks, it jumps and on most of the clicks nothing happens even Debug.Log("Now Jumping!!"); is not getting printed every time I hit J. How can I fix this?
I solved this problem. You have no choice but to add physics to the character controller. This is a simple code that has the same feature, but you should coordinate the movement and jump.
public class Player : MonoBehaviour
{
private Vector3 playerVelocity;
private CharacterController _controller;
public float jumpPower = 1f; // 1 is ok for -9.8 gravity
void Start()
{
_controller = GetComponent<CharacterController>();
}
void Update()
{
playerVelocity += Physics.gravity * Time.deltaTime;
_controller.Move(playerVelocity);
if (_controller.isGrounded)
{
playerVelocity.y = Input.GetKeyDown(KeyCode.Space) ? jumpPower : 0;
}
}
}

Stop my first person character controller going through the wall in Unity using C#?

As seen in the video here: https://i.gyazo.com/ad45ef9e231fd2f9ec6d4cf76889aece.mp4
My code:
MouseLook.cs:
using UnityEngine;
using System.Collections;
public class MouseLook : MonoBehaviour
{
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 3F;
public float sensitivityY = 3F;
public Camera playerCamera;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
private float rotationX = 0F;
private float rotationY = 0F;
private Quaternion originalRotation;
void Update()
{
if (axes == RotationAxes.MouseXAndY)
{
rotationX += Input.GetAxis("Mouse X") * sensitivityX;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationX = ClampAngle(rotationX, minimumX, maximumX);
rotationY = ClampAngle(rotationY, minimumY, maximumY);
Quaternion xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
Quaternion yQuaternion = Quaternion.AngleAxis(rotationY, -Vector3.right);
transform.localRotation = originalRotation * xQuaternion * yQuaternion;
}
if (axes == RotationAxes.MouseX)
{
rotationX += Input.GetAxis("Mouse X") * sensitivityX;
rotationX = ClampAngle(rotationX, minimumX, maximumX);
Quaternion xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
transform.localRotation = originalRotation * xQuaternion;
}
if (axes == RotationAxes.MouseY || playerCamera != null)
{
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = ClampAngle(rotationY, minimumY, maximumY);
Quaternion yQuaternion = Quaternion.AngleAxis(-rotationY, Vector3.right);
if (playerCamera != null)
{
playerCamera.transform.localRotation = originalRotation * yQuaternion;
}
else
{
transform.localRotation = originalRotation * yQuaternion;
}
}
}
void Start()
{
/*
if (gameObject.GetComponent<Rigidbody>())
{
gameObject.GetComponent<Rigidbody>().freezeRotation = true;
}
*/
originalRotation = transform.localRotation;
}
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
{
angle += 360F;
}
if (angle > 360F)
{
angle -= 360F;
}
return Mathf.Clamp(angle, min, max);
}
}
FirstPersonController.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using Cursor = UnityEngine.Cursor;
public class FirstPersonController : MonoBehaviour
{
private float speed = 5;
private float jumpPower = 4;
Rigidbody rb;
CapsuleCollider col;
public GameObject crossHair;
bool isActive;
float HorizontalInput;
float VerticalInput;
void Start()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
rb = GetComponent<Rigidbody>();
col = GetComponent<CapsuleCollider>();
crossHair = GameObject.FindWithTag("CrossHair");
}
void Update()
{
HorizontalInput = Input.GetAxisRaw("Horizontal");
VerticalInput = Input.GetAxisRaw("Vertical");
if (Input.GetKeyDown("escape"))
{
Cursor.lockState = CursorLockMode.None;
}
if (Input.GetButtonDown("Sprint"))
{
speed = 15;
}
if (Input.GetButtonUp("Sprint"))
{
speed = 5;
}
if (Input.GetKeyDown(KeyCode.H))
{
isActive = !isActive;
}
if (isActive)
{
crossHair.SetActive(true);
}
else
{
crossHair.SetActive(false);
}
}
void FixedUpdate()
{
Vector3 xMovement = transform.right * speed * HorizontalInput * Time.deltaTime;
Vector3 zMovement = transform.forward * speed * VerticalInput * Time.deltaTime;
rb.velocity = new Vector3(HorizontalInput, 0, VerticalInput) * speed;
if (isGrounded() && Input.GetButtonDown("Jump"))
{
rb.AddForce(Vector3.up * jumpPower, ForceMode.Impulse);
}
}
private bool isGrounded()
{
return Physics.Raycast(transform.position, Vector3.down, col.bounds.extents.y + 0.1f);
}
}
Is there anything wrong I am doing in this code, if so how do I fix it?
Entire project can be downloaded here: https://github.com/Some-T/FirstPersonController-CSharp
Project has relevant colliders and rigidbodies set up!
Someone has advised me to use shapecast, but I believe that may incorrect? I can't see how that would work as my player does not have character controller component added to it?
Overall how do I stop my first person character controller going through the wall like in the initial video specified above?
Upon further research I have discovered the following:
The answer is to use:
https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html as a quick fix.
But definitively for flawlessness use:
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
As to how in C# I am not so sure, but here is a screen shot I did in bolt asset.
Currently I have movmement working with velocity but it does not work properly, not sure as to why? So overall my question now is how do I get movement working using velocity? I added a line in FirstPersonController.cs that moves the character using velocity of rb.velocity = new Vector3(HorizontalInput, 0, VerticalInput) * speed; so my only question and issue now is my player does not move in the direction the camera on my player is facing so I am not sure how to fix this specific thing overall?
In your project code is different from one that you provided here.
Try to enable rigidbody`s rotation constraint - freeze X and Z rotation, leave only Y. When you rotate your capsule collider (as it works in your project), it can "climb" on a wall.
Do the isGrounded check when you move, and lock movement, if not grounded.
Try to increase Collider.contactOffset
If above does not helps, try to use Rigidbody.velocity instead of Rigidbody.MovePosition.
You can also reduce Rigidbody.drag
In general, pretty good technique is to use NavMesh for movement - in this way, you able to explicitly lock player from movement outside of navmesh surface. But, of course, it doesn`t fit to many gameplays.
Hope, it helps.
upd
You move your player like this:
void FixedUpdate()
{
Vector3 xMovement = transform.right * speed * HorizontalInput * Time.deltaTime;
Vector3 zMovement = transform.forward * speed * VerticalInput * Time.deltaTime;
}
Note, that you not even apply it to rigidbody;
But you get your input this way:
float HorizontalInput = Input.GetAxis("Horizontal");
float VerticalInput = Input.GetAxis("Vertical");
in Update, so input just stays inside Update, and does not applied at all. You declared your variables twice, once on class top, another in Update().

Unity Raycasting problem in some part of the scene

I started doing some simple stuff in Unity (goal is to make a great game) so I made a simple Player Controller.
public class PlayerController : MonoBehaviour
{
public float walkingSpeed;
public float jumpSpeed;
public bool jumpFlag = false;
public float maxJumpDistance = 1.0f;
Rigidbody rb;
Collider col;
Vector3 playerSize;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
col = GetComponent<Collider>();
playerSize = col.bounds.size;
}
// Update is called once per frame
void FixedUpdate()
{
WalkHandler();
JumpHandler();
}
void WalkHandler()
{
float horizonstalAxis = Input.GetAxis("Horizontal");
float verticalAxis = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(-horizonstalAxis * walkingSpeed * Time.deltaTime, 0, -verticalAxis * walkingSpeed * Time.deltaTime);
rb.MovePosition(transform.position += movement);
}
void JumpHandler()
{
float jumpAxis = Input.GetAxis("Jump");
//Debug.Log(jumpAxis);
if (jumpAxis > 0)
{
bool isGrounded = CheckGrounded();
if (jumpFlag != true && isGrounded)
{
jumpFlag = true;
Vector3 jumpVector = new Vector3(0, jumpSpeed * Time.deltaTime, 0);
rb.AddForce(jumpVector, ForceMode.VelocityChange);
}
}
else
{
jumpFlag = false;
}
}
bool CheckGrounded()
{
Vector3 checkerPoint = transform.position + new Vector3(0, -playerSize.y / 2, 0);
bool grounded = Physics.Raycast(checkerPoint, -Vector3.up, maxJumpDistance);
return grounded;
}
I came across a wierd problem. In some parts of the scene my method JumpHandler is not working. After reaching some z coordinates, the CheckGrounded returns False instead of True, even though the Raycast direction is set down.
Can anyone help?

Player rotates,Camera rotates, but x,y,z stay the same?

So I am moving the camera around as so
public static CameraController Instance{ set; get; }
public Transform lookAt;
public Transform camTransform;
private Camera cam;
public const float Y_ANGLE_MIN = 0.0f;
public const float Y_ANGLE_MAX = 50.0f;
public float distance = 10.0f;
public float currentX = 0.0f;
public float currentY = 0.0f;
public float sensitivityX = 7.0f;
public float sensitivityY = 7.0f;
private void Start(){
Instance = this;
camTransform = transform;
cam = Camera.main;
}
private void Update(){
currentX += InputManager.SecondaryHorizontal ();
currentY += InputManager.SecondaryVertical ();
currentY = Mathf.Clamp (currentY, Y_ANGLE_MIN, Y_ANGLE_MAX);
}
private void LateUpdate(){
Vector3 dir = new Vector3 (0, 0, -distance);
Quaternion rotation = Quaternion.Euler(currentY,currentX,0);
camTransform.position = lookAt.position + rotation * dir;
camTransform.LookAt (lookAt.position);
this.transform.position += Vector3.up;
}
I am rotating my player around as the camera rotates as so
private void Update(){
this.transform.eulerAngles = CameraController.Instance.camTransform.eulerAngles;
}
I am expecting that when my player is rotated to the left that pressing the MainVertical() (attached to the WASD controls & joystick X,Y axis)
public static float MainVertical(){
float r = 0.0f;
r += Input.GetAxis ("J_MainVertical");
r += Input.GetAxis ("K_MainVertical");
return Mathf.Clamp (r, -1.0f, 1.0f);
}
will rotate move the player forward in the direction that is now the forward direction
However the character continues to move forward in what was originally the forward direction.
I can only assume that the issue is though the forward axis has changed for the object the x,y,z in world space doesnt change and thats what MainVertical() is still accessing
As requested here is the code for my character movement
private CharacterController controller;
private Animator anim;
//Speed settings
private float walkingSpeed = 5.0f;
private float runningSpeed = 7.5f;
//Jump and gravity settings
private float verticalVelocity;
private float gravity = 14.0f;
private float jumpForce = 10.0f;
private void Start(){
controller = GetComponent<CharacterController> ();
anim = GetComponent<Animator> ();
}
private void Update(){
this.transform.eulerAngles = CameraController.Instance.camTransform.eulerAngles;
Jump ();
Vector3 moveVector = InputManager.MainJoystick ();
moveVector.x = moveVector.x * walkingSpeed;
moveVector.y = verticalVelocity;
moveVector.z = moveVector.z * walkingSpeed;
controller.Move (moveVector * Time.deltaTime);
Vector3 camForward = Vector3.Scale (CameraController.Instance.camTransform.forward, new Vector3 (1, 0, 1)).normalized;
if (moveVector.x != 0 || moveVector.z != 0) {
anim.SetBool ("IsIdle", false);
anim.SetBool ("IsWalking", true);
} else {
anim.SetBool ("IsIdle", true);
anim.SetBool ("IsWalking", false);
}
}
protected void Jump(){
if (controller.isGrounded) {
verticalVelocity = -gravity * Time.deltaTime;
if (InputManager.AButton()) {
anim.SetTrigger ("Jump");
verticalVelocity = jumpForce;
}
} else {
verticalVelocity -= gravity * Time.deltaTime;
//anim.SetTrigger ("Landing");
}
}
}
And here is my input manager
// -- Axis
public static float MainHorizontal(){
float r = 0.0f;
r += Input.GetAxis ("J_MainHorizontal");
r += Input.GetAxis ("K_MainHorizontal");
return Mathf.Clamp (r, -1.0f, 1.0f);
}
public static float MainVertical(){
float r = 0.0f;
r += Input.GetAxis ("J_MainVertical");
r += Input.GetAxis ("K_MainVertical");
return Mathf.Clamp (r, -1.0f, 1.0f);
}
public static Vector3 MainJoystick(){
return new Vector3 (MainHorizontal (), 0, MainVertical ());
}
public static float SecondaryHorizontal(){
float r = 0.0f;
r += Input.GetAxis ("J_SecondaryHorizontal");
r += Input.GetAxis ("Mouse X");
return Mathf.Clamp (r, -1.0f, 1.0f);
}
public static float SecondaryVertical(){
float r = 0.0f;
r += Input.GetAxis ("J_SecondaryVertical");
r += Input.GetAxis ("Mouse Y");
return Mathf.Clamp (r, -1.0f, 1.0f);
}
public static Vector3 SecondaryJoystick(){
return new Vector3 (SecondaryHorizontal (), SecondaryVertical (), 0);
}
// -- Buttons
public static bool AButton(){
return Input.GetButtonDown ("A_Button");
}
public static bool BButton(){
return Input.GetButtonDown ("B_Button");
}
public static bool XButton(){
return Input.GetButtonDown ("X_Button");
}
public static bool YButton(){
return Input.GetButtonDown ("Y_Button");
}
this is correct:
I can only assume that the issue is though the forward axis has
changed for the object the x,y,z in world space doesnt change and
thats what MainVertical() is still accessing
you are confusing this.transform from player and Input.GetAxis - they are 2 totally different things, unrelated to each other. imagine FIFA, where you have 11 soccer players, each has his own this.transform but you still have only one Input.GetAxis
try this:
private void Update(){
this.transform.eulerAngles = CameraController.Instance.camTransform.eulerAngles;
//Vector3 moveVector = Quaternion.Euler(this.transform.eulerAngles) * InputManager.MainJoystick ();
// EDIT
Vector3 moveVector = InputManager.MainJoystick ();
moveVector = transform.TransformDirection(moveVector);
moveVector.x = moveVector.x * walkingSpeed;
moveVector.y = verticalVelocity;
moveVector.z = moveVector.z * walkingSpeed;
controller.Move (moveVector * Time.deltaTime);
}
in general, try to separate your player code from your input code - try to imagine how you would control 11 soccer players with 1 controller
EDIT:
used code from https://docs.unity3d.com/ScriptReference/CharacterController.Move.html

Categories