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

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

Related

Creating boundaries for Camera with with mouse drag

I've made an orthographic camera that is moving by dragging a mouse but can't understand how to create a boundaries for it. It seems that I have to use Mathf.Clamp but can't find out how.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamController : MonoBehaviour
{
public Transform cameraTransform;
public float movementSpeed;
public float movementTime;
public Vector3 newPosition;
public Vector3 dragStartPosition;
public Vector3 dragCurrentPosition;
public Camera cam;
public float maxZoom = 5;
public float minZoom = 20;
public float sensitivity = 1;
public float speed = 30;
float targetZoom;
public float minX = 100;
public float maxX = 120;
// Start is called before the first frame update
void Start()
{
newPosition = transform.position;
}
// Update is called once per frame
void Update()
{
HandleMouseInput();
HandleMovementInput();
{
targetZoom -= Input.mouseScrollDelta.y * sensitivity;
targetZoom = Mathf.Clamp(targetZoom, maxZoom, minZoom);
float newSize = Mathf.MoveTowards(cam.orthographicSize, targetZoom, speed * Time.deltaTime);
cam.orthographicSize = newSize;
}
}
void HandleMouseInput()
{
if (Input.GetMouseButtonDown(0))
{
Plane plane = new Plane(Vector3.up, Vector3.zero);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float entry;
if (plane.Raycast(ray, out entry))
{
dragStartPosition = ray.GetPoint(entry);
}
}
if (Input.GetMouseButton(0))
{
Plane plane = new Plane(Vector3.up, Vector3.zero);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float entry;
if (plane.Raycast(ray, out entry))
{
dragCurrentPosition = ray.GetPoint(entry);
newPosition = transform.position + dragStartPosition - dragCurrentPosition;
}
}
newPosition = Mathf.Clamp(minX, minX);
}
void HandleMovementInput()
{
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
newPosition += (transform.forward * movementSpeed);
}
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
newPosition += (transform.forward * -movementSpeed);
}
if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
{
newPosition += (transform.right * movementSpeed);
}
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
{
newPosition += (transform.right * -movementSpeed);
}
transform.position = Vector3.Lerp(transform.position, newPosition, Time.deltaTime * movementTime);
}
}
newPosition = Mathf.Clamp(minX, minX);
You can't clamp with only two parameters .. you need a current, a min and a max value .. And you can't just convert a float which is what Mathf.Clamp returns into a Vector3 (3 floats)
I think what you meant was rather something like e.g.
newPosition.x = Mathf.Clamp(newPosition.x, minX, maxX);
However, right after that in HandleMovementInput you overwrite it anyway so you might want to change the moment when you are clamping and rather do it right before applying the new position.

How to let camera's vertical rotation move the camera up and down?

I have a player in the game, which I can move using the keyboard and rotate only on the horizontal axis using the mouse. That means, I can aim only horizontally and I can not aim it up and down.
I have the Main Camera and another VM Camera from Cinemachine. The current state of the game is like this:
On the horizontal axis, I rotate the player, but on the vertical axis I only want the player's camera/FOV to be moved up and down.
My movement script attached to the player is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController characterController;
public float speed = 35f;
public Animator animator;
// camera and rotation
public Transform cameraHolder;
public float mouseSensitivity = 2f;
public float upLimit = 50;
public float downLimit = -50;
// gravity
private float gravity = 9.87f;
private float verticalSpeed = 0;
void Update()
{
Move();
Rotate();
}
public void Rotate()
{
float horizontalRotation = Input.GetAxis("Mouse X");
float verticalRotation = Input.GetAxis("Mouse Y");
transform.Rotate(0, horizontalRotation * mouseSensitivity, 0);
cameraHolder.Rotate(-verticalRotation * mouseSensitivity, 0, 0);
Vector3 currentRotation = cameraHolder.localEulerAngles;
if (currentRotation.x > 180) currentRotation.x -= 360;
currentRotation.x = Mathf.Clamp(currentRotation.x, upLimit, downLimit);
cameraHolder.localRotation = Quaternion.Euler(currentRotation);
}
private void Move()
{
float horizontalMove = Input.GetAxis("Horizontal");
float verticalMove = Input.GetAxis("Vertical");
if (characterController.isGrounded) verticalSpeed = 0;
else verticalSpeed -= gravity * Time.deltaTime;
Vector3 gravityMove = new Vector3(0, verticalSpeed, 0);
Vector3 move = transform.forward * verticalMove + transform.right * horizontalMove;
characterController.Move(speed * Time.deltaTime * move + gravityMove * Time.deltaTime);
}
}
This is the code i use, it works for me, it's super easy to implement, and stops moving the camera when you aren't focusing the game, is the script from one of Brackey's tutorials modified for this purpose:
using UnityEngine;
public class CameraController : MonoBehaviour
{
public PlayerController player;
public float sensitivity = 150f;
public float clampAngle = 85f;
public bool look = true;
private float verticalRotation;
private float horizontalRotation;
private void Start()
{
verticalRotation = transform.localEulerAngles.x;
horizontalRotation = player.transform.eulerAngles.y;
// Defines the state of the cursor
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
// Looks around if the user is in the window
if (look)
{
Look();
}
Debug.DrawRay(transform.position, transform.forward * 2, Color.red);
// If the player presses ESC while in the game, it unlocks the cursor
if (look && Input.GetKeyDown(KeyCode.Escape))
{
look = false;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
else if (Input.GetMouseButtonDown(0) && !look)
{
look = true;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
private void Look()
{
float _mouseVertical = -Input.GetAxis("Mouse Y");
float _mouseHorizontal = Input.GetAxis("Mouse X");
verticalRotation += _mouseVertical * sensitivity * Time.deltaTime;
horizontalRotation += _mouseHorizontal * sensitivity * Time.deltaTime;
verticalRotation = Mathf.Clamp(verticalRotation, -clampAngle, clampAngle);
transform.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);
player.transform.rotation = Quaternion.Euler(0f, horizontalRotation, 0f);
}
}

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().

Rotating Rigidbody controller

There is my script Rigidbody controller -
public float Speed = 5f;
public float JumpHeight = 2f;
public float GroundDistance = 0.2f;
public float DashDistance = 5f;
public LayerMask Ground;
private Rigidbody _body;
private Vector3 _inputs = Vector3.zero;
private bool _isGrounded = true;
private Transform _groundChecker;
void Start()
{
_body = GetComponent<Rigidbody>();
_groundChecker = transform.GetChild(0);
}
void Update()
{
_isGrounded = Physics.CheckSphere(_groundChecker.position, GroundDistance, Ground, QueryTriggerInteraction.Ignore);
_inputs = Vector3.zero;
_inputs.x = Input.GetAxis("Horizontal");
_inputs.z = Input.GetAxis("Vertical");
if (_inputs != Vector3.zero)
transform.forward = _inputs;
if (Input.GetButtonDown("Jump") && _isGrounded)
{
_body.AddForce(Vector3.up * Mathf.Sqrt(JumpHeight * -2f * Physics.gravity.y), ForceMode.VelocityChange);
}
if (Input.GetButtonDown("Sprint"))
{
Vector3 dashVelocity = Vector3.Scale(transform.forward, DashDistance * new Vector3((Mathf.Log(1f / (Time.deltaTime * _body.drag + 1)) / -Time.deltaTime), 0, (Mathf.Log(1f / (Time.deltaTime * _body.drag + 1)) / -Time.deltaTime)));
_body.AddForce(dashVelocity, ForceMode.VelocityChange);
}
}
void FixedUpdate()
{
_body.MovePosition(_body.position + _inputs * Speed * Time.fixedDeltaTime);
}
What the best way to make a turn on y in the direction of the camera ? That is,the player turns to the side where the mouse is turned? Is it in fixedUpdate or update?
This is the camera script:
public float Smoothness = 0.3F;
public Vector2 Sensitivity = new Vector2(4, 4);
public Vector2 LimitX = new Vector2(-70, 80);
private Vector2 NewCoord;
public Vector2 CurrentCoord;
private Vector2 vel;
public GameManager GameMangerS;
public Transform Target;
public float TransformSpeed;
public Animator CameraAnimator;
void Update()
{
NewCoord.x = Mathf.Clamp(NewCoord.x, LimitX.x, LimitX.y);
NewCoord.x -= Input.GetAxis("Mouse Y") * Sensitivity.x;
NewCoord.y += Input.GetAxis("Mouse X") * Sensitivity.y;
CurrentCoord.x = Mathf.SmoothDamp(CurrentCoord.x, NewCoord.x, ref vel.x, Smoothness / 2);
CurrentCoord.y = Mathf.SmoothDamp(CurrentCoord.y, NewCoord.y, ref vel.y, Smoothness / 2);
transform.rotation = Quaternion.Euler(CurrentCoord.x, CurrentCoord.y, 0);
}
And added this line to the controller script -
void FixedUpdate()
{
_body.MovePosition(_body.position + _inputs * Speed * Time.fixedDeltaTime);
transform.rotation = Quaternion.Euler(0, MainCamera.CurrentCoord.y, 0);
}
When I'm standing the player normally rotates, but when I start to move, all rotations are reset and the player is not moving.
Update
Simple Rotation can be achieved using transform.Rotate().
Example:
this.transform.Rotate(Vector3.up, 30);
This example is gonna rotate the transform by 30° around the Vector that points upwards.
LookAtMouse:
To make your object turn towards the mouse, you need the ScreenToWorldSpace() method from your camera. In order to convert the ScreenCoordinates into your WorldCoordinates.
Example:
Please note:
You have to set the camera instance! If you don't add that, you'll get a NullReferenceException.
This Snippets shall only show the steps needed to achieve the behavior you wish.
You will have to find out yourself how to integrate that lines of code into your code to make it work. Consider what Programmer told you in the comment when integrating that.
Vector3 mousePosition = Input.mousePosition; //get the screenSpaceMousePosition
Vector3 worldPosition = this.camera.ScreenToWorldPoint(mousePosition); //convert it into worldSpacePosition
Vector3 calculatedDirection = worldPosition - transform.position; //calucate the looking direction
calculatedDirection.y = 0;
Quaternion rotation = Quaternion.LookRotation(calculatedDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime);

Continue moving in the same direction as the last input

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.

Categories