Only move the "z" axis - c#

I have this Recoil script, the only problem is that the code moves my gun to all of the axes but I only want to move my gun on the Z-axis. I couldn't find any solution for it. Thanks! Here is the code:
using UnityEngine;
using System.Collections;
public class Recoil : MonoBehaviour {
public Vector3 hipPos;
public Vector3 zoomPos;
public float speed = 4f;
void Update () {
if(Input.GetMouseButton(0)) {
transform.localPosition = Vector3.Lerp(transform.localPosition, zoomPos, Time.deltaTime * speed);
transform.localPosition = Vector3.Lerp(transform.localPosition, hipPos, Time.deltaTime * speed);
}
else {
transform.localPosition = Vector3.Lerp(transform.localPosition, hipPos, Time.deltaTime * speed);
}
}
}

Get the gun to move towards the desired z position, but keep the x and y positions the same.
using UnityEngine;
using System.Collections;
public class Recoil : MonoBehaviour {
public Vector3 hipPos;
public Vector3 zoomPos;
public float speed = 4f;
private Vector3 localPosition
void Update () {
if(Input.GetMouseButton(0)) {
transform.localPosition = Vector3.Lerp(transform.localPosition, new Vector3(transform.localPosition.x, transform.localPosition.y, zoomPos.z), Time.deltaTime * speed);
transform.localPosition = Vector3.Lerp(transform.localPosition, new Vector3(transform.localPosition.x, transform.localPosition.y, hipPos.z) , Time.deltaTime * speed);
}
else {
transform.localPosition = Vector3.Lerp(transform.localPosition, new Vector3(transform.localPosition.x, transform.localPosition.y, hipPos.z), Time.deltaTime * speed);
}
}
}
To understand how lerp works, refer to the Unity documentation for it here.

Related

Top down game in Unity. Player can't stop moving

i've following issue. I'm trying to make game with top down view (something like first GTA game). The problem is when i press the key my player is moving, but can't stop. Here you can see my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovemenet : MonoBehaviour
{
private Rigidbody2D m_Rigidbody;
private Transform playerTransform;
public float m_Speed = 100.0f;
// Start is called before the first frame update
void Start()
{
m_Rigidbody = GetComponent<Rigidbody2D>();
playerTransform = GameObject.Find("Player").transform;
}
// Update is called once per frame
void FixedUpdate()
{
Vector3 playerPos = playerTransform.eulerAngles;
if (Input.GetKey(KeyCode.UpArrow))
{
m_Rigidbody.velocity= transform.up * Time.deltaTime * m_Speed;
}
if (Input.GetKey(KeyCode.DownArrow))
{
m_Rigidbody.velocity = transform.up * Time.deltaTime * (-m_Speed);
}
if (Input.GetKey(KeyCode.RightArrow))
{
transform.Rotate(0, 0, -1 * m_Speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.Rotate(0, 0, 1 * m_Speed * Time.deltaTime);
}
}
}
'''
Can you please tell me how to fix it? Thanks for your answers.
Note that in general a velocity already is a value in absolute units per second and you don't want to multiply by Time.deltaTime in that case.
Also in general whenever dealing with Physics I wouldn't use transform at all but rather do everything via the Rigidbody.
And then simply when you don't press a key do
if (Input.GetKey(KeyCode.UpArrow))
{
m_Rigidbody.velocity = Quaternion.Euler(0, 0, m_Rigidbody.rotation) * Vector3.up * m_Speed;
}
else if (Input.GetKey(KeyCode.DownArrow))
{
m_Rigidbody.velocity = Quaternion.Euler(0, 0, m_Rigidbody.rotation) * Vector3.down * m_Speed;
}
else
{
m_Rigidbody.velocity = Vector2.zero;
}
For the rotation I would also rather go
m_Rigidbody.rotation += m_Speed * Time.deltaTime;
and
m_Rigidbody.rotation -= m_Speed * Time.deltaTime;

Problem with Mathf.Clamp and rotation in Unity

I have a problem with my camera movement. I want to limit my camera rotation, but I don't know how to do this. I searched for a solution, but I was not able to find one.
In my current code, my camera rotates rapidly in any direction and I don't know how to implement the Mathf.Clamp correctly.
Here is my code:
public float rightSpeed = 20.0f;
public float leftSpeed = -20.0f;
public float rotationLimit = 0.0f;
void Update()
{
//EdgeScrolling
float edgeSize = 40f;
if (Input.mousePosition.x > Screen.width - edgeSize)
{
//EdgeRight
transform.RotateAround(this.transform.position, Vector3.up, rotationLimit += rightSpeed * Time.deltaTime);
}
if (Input.mousePosition.x < edgeSize)
{
//EdgeLeft
transform.RotateAround(this.transform.position, Vector3.up, rotationLimit -= leftSpeed * Time.deltaTime);
}
rotationLimit = Mathf.Clamp(rotationLimit, 50f, 130f);
}
RotateAround method rotates by an angle. It doesn't assign the angle value you pass it. In this case I would suggest using a different approach. Instead of RotateAround method use the eulerAngles property and assign the rotation values directly.
Example
using UnityEngine;
public class TestScript : MonoBehaviour
{
public float rightSpeed = 20.0f;
public float leftSpeed = -20.0f;
private void Update()
{
float edgeSize = 40f;
if (Input.mousePosition.x > Screen.width - edgeSize)
RotateByY(rightSpeed * Time.deltaTime);
else if (Input.mousePosition.x < edgeSize)
RotateByY(leftSpeed * Time.deltaTime);
}
public void RotateByY(float angle)
{
float newAngle = transform.eulerAngles.y + angle;
transform.eulerAngles = new Vector3(
transform.eulerAngles.x,
Mathf.Clamp(newAngle, 50f, 130f),
transform.eulerAngles.z);
}
}

Is there a way to make a the camera orbit around a GameObject while updating rotation?

I've been trying to code a car in Unity 5 which can move like a normal car but have the camera orbit around it. I have this working but the camera does not keep it's orbit position when the car turns. Example: I'm looking at the back of the car, and I turn right. I will now be looking at the right side of the car. Is there any way to make the camera still be in the same position, relative to the car.
I got the car movement from this tutorial, but I didn't like the camera movement in it, I wanted the camera to orbit the car. I followed this one for the camera movement. However, I am trying to modify it so the camera turns with the car and doesn't reset to the back of the car
CameraManager.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraManager : MonoBehaviour
{
public InputManager im;
public bool lockCursor;
public float distance = 5f;
public float mouseSensitivity = 10f;
public Transform target;
public Vector2 pitchMinMax = new Vector2 (-40, 85);
public float rotationSmoothTime = 0.12f;
Vector3 rotationSmoothVelocity;
Vector3 currentRotation;
float yaw;
float pitch;
void Start()
{
im = GetComponent<InputManager>();
if (lockCursor)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
// Update is called once per frame
void LateUpdate()
{
yaw += (Input.GetAxis("Mouse X")) * mouseSensitivity;
pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity;
pitch = Mathf.Clamp(pitch, pitchMinMax.x, pitchMinMax.y);
currentRotation = Vector3.SmoothDamp(currentRotation, new Vector3(pitch, yaw), ref rotationSmoothVelocity, rotationSmoothTime);
transform.eulerAngles = currentRotation;
print(target.transform.forward);
transform.position = target.position - transform.forward * distance;
}
}
InputManager.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputManager : MonoBehaviour
{
public float throttle;
public float steer;
// Update is called once per frame
void Update()
{
throttle = Input.GetAxis("Vertical");
steer = Input.GetAxis("Horizontal");
print(steer);
}
}
CarController.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(InputManager))]
[RequireComponent(typeof(Rigidbody))]
public class CarController : MonoBehaviour
{
public InputManager im;
public List<WheelCollider> throttleWheels;
public List<WheelCollider> steeringWheels;
public float strengthCo = 10000f; //Strength Coefficent
public float maxTurn = 20f;
public Transform CM;
public Rigidbody rb;
// Start is called before the first frame update
void Start()
{
im = GetComponent<InputManager>();
rb = GetComponent<Rigidbody>();
if (CM)
{
rb.centerOfMass = CM.position;
}
}
// Update is called once per frame
void FixedUpdate()
{
foreach (WheelCollider wheel in throttleWheels)
{
wheel.motorTorque = strengthCo * Time.deltaTime * im.throttle;
}
foreach (WheelCollider wheel in steeringWheels)
{
wheel.steerAngle = maxTurn * im.steer;
}
}
}
You can use Quaternion.Euler(currentRotation) as a relative rotation to apply to target.rotation, and apply it with target.rotation * Quaternion.Euler(currentRotation):
void LateUpdate()
{
yaw += (Input.GetAxis("Mouse X")) * mouseSensitivity;
pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity;
pitch = Mathf.Clamp(pitch, pitchMinMax.x, pitchMinMax.y);
currentRotation = Vector3.SmoothDamp(currentRotation, new Vector3(pitch, yaw), ref rotationSmoothVelocity, rotationSmoothTime);
transform.rotation = target.rotation * Quaternion.Euler(currentRotation);
print(target.transform.forward);
transform.position = target.position - transform.forward * distance;
}

Gameobject does not clamp but rather jitters

I am trying to clamp the value of y for my game object to be 4 and -4 but it keeps jumping to the ymax and ymin. and the only reason i can think of is because of the last line code. i am only clamping the y values because the x and z values are not changed in the game. the game is similar to pong.
using UnityEngine;
using System.Collections;
public class Movement1 : MonoBehaviour
{
public Vector3 Pos;
void Start ()
{
Pos = gameObject.transform.localPosition;
}
public float yMin, yMax;
void Update ()
{
if (Input.GetKey (KeyCode.W)) {
transform.Translate (Vector3.up * Time.deltaTime * 10);
}
if (Input.GetKey (KeyCode.S)) {
transform.Translate (Vector3.down * Time.deltaTime * 10);
}
Pos.y = Mathf.Clamp(Pos.y,yMin,yMax);
gameObject.transform.localPosition = Pos;
}
}
The Pos.y assignment never happens, because you can't change just the y-value; you have to make a new Vector3. Try the following:
using UnityEngine;
using System.Collections;
public class Movement1 : MonoBehaviour
{
public float yMin, yMax; // be sure to set these in the inspector
void Update ()
{
if (Input.GetKey (KeyCode.W)) {
transform.Translate (Vector3.up * Time.deltaTime * 10);
}
if (Input.GetKey (KeyCode.S)) {
transform.Translate (Vector3.down * Time.deltaTime * 10);
}
float clampedY = Mathf.Clamp(transform.localPosition.y,yMin,yMax);
transform.localPosition = new Vector3 (transform.localPosition.x, clampedY, transform.localPosition.z);
}
}
You didn't initialize any values for the yMin, yMax.
Also, you should put an else if for the second Translate, otherwise pressing both could cause jitters.
But really, it should be more like this:
using UnityEngine;
using System.Collections;
public class Movement1 : MonoBehaviour
{
public Vector3 Pos;
public float speed = 10f;
public float yMin = 10f;
public float yMax = 50f;
void Update ()
{
Pos = gameObject.transform.localPosition;
if (Input.GetKey (KeyCode.W))
Pos += (Vector3.up * Time.deltaTime * speed);
if (Input.GetKey (KeyCode.S))
Pos += (Vector3.down * Time.deltaTime * speed);
Pos.y = Mathf.Clamp(Pos.y,yMin,yMax);
gameObject.transform.localPosition = Pos;
}
}

Unity fps rotation camera

In my game I have a camera and I want to have an FPS like rotation attached to this camera.
So if I move my cursor to the left, I want my cam to rotate to the left. If I move my cursor up, then the cam should look up, etc.
I currently have it partially working. I can look left and right, up, and down. The problem occurs when I look down and then move my cursor left and right. It then gives me a "Roll" effect.
See this video to see exactly what I mean:
http://www.screencast.com/t/Phedh8H0K13
Obviously when I look down I still want to have a "Yaw" effect instead of a "Roll" effect. Anyone any idea how to do that? This is what I have so far:
// Update is called once per frame
public override void update ()
{
this.camera.transform.rotation *=
Quaternion.AngleAxis( Time.deltaTime * sensitivityRoll * Input.GetAxis("Vertical"), Vector3.forward );
this.camera.transform.rotation *=
Quaternion.AngleAxis( Time.deltaTime * sensitivityYaw * Input.GetAxis("Mouse X"), Vector3.up );
this.camera.transform.rotation *=
Quaternion.AngleAxis( Time.deltaTime * sensitivityPitch * Input.GetAxis("Mouse Y"), Vector3.left );
}
I just found my answer in this topic:
http://forum.unity3d.com/threads/109250-Looking-with-the-Mouse?highlight=person+camera
The code from that topic:
C# Mono code:
using UnityEngine;
using System.Collections;
/// MouseLook rotates the transform based on the mouse delta.
/// Minimum and Maximum values can be used to constrain the possible rotation
/// To make an FPS style character:
/// - Create a capsule.
/// - Add the MouseLook script to the capsule.
/// -> Set the mouse look to use LookX. (You want to only turn character but not tilt it)
/// - Add FPSInputController script to the capsule
/// -> A CharacterMotor and a CharacterController component will be automatically added.
/// - Create a camera. Make the camera a child of the capsule. Reset it's transform.
/// - Add a MouseLook script to the camera.
/// -> Set the mouse look to use LookY. (You want the camera to tilt up and down like a head. The character already turns.)
[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseLook : MonoBehaviour {
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15F;
public float sensitivityY = 15F;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
float rotationY = 0F;
void Update ()
{
if (axes == RotationAxes.MouseXAndY)
{
float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
}
else if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
}
else
{
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
}
}
void Start ()
{
//if(!networkView.isMine)
//enabled = false;
// Make the rigid body not change rotation
//if (rigidbody)
//rigidbody.freezeRotation = true;
}
}
Simple Script, Not Sure it will work with you, might as well give it a try
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Threading;
using UnityEngine;
public class mouse_lookat : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody;
float xRotation = 0f;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
using UnityEngine;
public class CameraRotator : MonoBehaviour
{
[SerializeField] private Transform _head;
[SerializeField] private float _sensitivity;
[SerializeField] private bool _invertVertical;
private void Update()
{
var deltaMouse = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y");
Vector2 deltaRotation = deltaMouse * _sensitivity;
deltaRotation.y *= _invertVertical ? 1.0f : -1.0f;
float pitchAngle = _head.localEulerAngles.x;
// turns 270 deg into -90, etc
if (pitchAngle > 180)
pitchAngle -= 360;
pitchAngle = Mathf.Clamp(pitchAngle + deltaRotation.y, -90.0f, 90.0f);
transform.Rotate(Vector3.up, deltaRotation.x);
_head.localRotation = Quaternion.Euler(pitchAngle, 0.0f, 0.0f);
}
}
i created 2 scripts for my FPS project that work flawlessly for my movement (currently havnt added jump mechanics) and it seems like youve overcomplicated alot of things that can be quite simple and straight forward.
im also new to coding so please correct me if im wrong heres my code
// this is in the player script which i put on an empty parent object of the camera and player sprite
public class player : MonoBehaviour
{
[Header("player Movement")]
[SerializeField] float moveSpeed = 5f;
[SerializeField] public float mouseSensitivity = 5f;
Rigidbody rigidBody;
// Use this for initialization
void Start()
{
}
void Update()
{
Move();
}
private void Move()
{
transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime);
transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime);
transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * mouseSensitivity);
}
//this is the camera movement script which i put on the camera(will also use this script to add a function to change from 1st person to 3rd person for certain abilities)
{
player player;
// Use this for initialization
void Start()
{
player = FindObjectOfType<player>();
}
// Update is called once per frame
void Update()
{
MoveView();
}
private void MoveView()
{
transform.Rotate(Vector3.left * Input.GetAxis("Mouse Y") * player.mouseSensitivity);
}
}

Categories

Resources