Gameobject does not clamp but rather jitters - c#

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;
}
}

Related

Only move the "z" axis

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.

Unity jump script delay

Im making a 3d game in unity, and so I made a cs script for movement of my charecter, walking and moveing the camera works fine, however when i added the jump function, it had a delay. You could press the jump button 5 times, with no result. Then you press it again, and it jumps. I cant figure out why this does this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController characterController;
public int speed = 6;
public float gravity = 9.87f;
private float verticalspeed = 0;
private Vector3 moveDirection = Vector3.zero;
public Transform Camera;
public float Sensitivity = 2f;
public float uplimit = -50;
public float downlimit = -50;
public float jumpspeed = 5.0f;
void Update()
{
move();
cameramove();
void cameramove()
{
float horizontal = Input.GetAxis("Mouse X");
float vertical = Input.GetAxis("Mouse Y");
transform.Rotate(0, horizontal * Sensitivity, 0);
Camera.Rotate(-vertical * Sensitivity, 0, 0);
Vector3 currentRotation = Camera.localEulerAngles;
if (currentRotation.x > 180) currentRotation.x -= 360;
currentRotation.x = Mathf.Clamp(currentRotation.x, uplimit, downlimit);
Camera.localRotation = Quaternion.Euler(currentRotation);
}
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);
if (characterController.isGrounded && Input.GetButton("Jump"))
{
moveDirection.y = jumpspeed;
}
moveDirection.y -= gravity * Time.deltaTime;
characterController.Move(moveDirection * Time.deltaTime);
}
}
}
Assuming your character has a RigidBody assigned to it, you can refer it on your script as,
public class PlayerMovement : MonoBehaviour
{
private Rigidbody myrigidbody;
void Start () {
myrigidbody = GetComponent<Rigidbody>();
}
}
Then you can pass the jumpspeed as a Vector3, and probably you might have to trigger your animation here as well.
if (characterController.isGrounded && Input.GetButton("Jump"))
{
characterController.isGrounded = false;
myrigidbody.AddForce(new Vector3(0, jumpspeed, 0));
// Trigger your animation, myanimator.SetTrigger("jump");
}
Unity character controller move documentation also contains jump function.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Example : MonoBehaviour
{
private CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
private float playerSpeed = 2.0f;
private float jumpHeight = 1.0f;
private float gravityValue = -9.81f;
private void Start()
{
controller = gameObject.AddComponent<CharacterController>();
}
void Update()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * playerSpeed);
if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}
// Changes the height position of the player..
if (Input.GetButtonDown("Jump") && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * 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);
}
}

Unity Player Controller - how to make it so it doesn't go upside down

This is my CamMouseLook script and I need it so when the player moves the mouse all the way up it doesnt turn upside down. I want him to be able to look up just not so much up that it turns the view upside down
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamMouseLook : MonoBehaviour {
Vector2 mouseLook;
Vector2 smoothV;
public float sensitivity = 5.0f;
public float smoothing = 2.0f;
GameObject character;
// Use this for initialization
void Start () {
character = this.transform.parent.gameObject;
}
// Update is called once per frame
void Update () {
var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
mouseLook += smoothV;
transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, character.transform.up);
}
}
What you can do is to lock the rotation in a specific axis. For example to limit in the Y and X axis so the player can only rotate from [-60,60] degrees you can use:
using System;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 70.0f;
public float clampAngle = 60.0f;
private float rotY = 0.0f; // rotation around the up/y axis
private float rotX = 0.0f; // rotation around the right/x axis
void Start ()
{
Vector3 rot = transform.localRotation.eulerAngles;
rotY = rot.y;
rotX = rot.x;
}
void Update ()
{
float mouseX = Input.GetAxis("Mouse X");
float mouseY = -Input.GetAxis("Mouse Y");
rotY += mouseX * mouseSensitivity * Time.deltaTime;
rotX += mouseY * mouseSensitivity * Time.deltaTime;
rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);
Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
transform.rotation = localRotation;
}
}
Now you can adapt this script to limit the rotation in the angle and the range you need

2D Flight simulator physics in Unity

I'm tring to implement a simple (but realistic as possible) 2D flight simulator in Unity using its 2D engine.
I have taken some sources around and tried to compile my own (without success) ... i must admit i'm a math and c# newbie; forgive my ignorance ..
Ideally i would like to achieve something like this :
http://runway.countlessprojects.com/prototype/index.html
Any ideas / corrections / suggestions welcome
using UnityEngine;
using System.Collections;
public class FlightControl : MonoBehaviour {
public float energy;
public float roll;
public float tilt;
public float yaw;
public float airspeed;
public float fall;
public float tip;
Rigidbody2D rb;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
void Start () {
}
void Update () {
energy = transform.position.y + GetComponent<Rigidbody2D>().velocity.magnitude;
}
void FixedUpdate () {
tilt = Mathf.Clamp (energy / 100, -8f, 5f);
tilt /= Time.deltaTime * 10;
if (Input.GetButton("Jump")) {
GetComponent<Rigidbody2D>().AddForce((Vector2)transform.up * Time.deltaTime * 10000);
}
transform.rotation = Quaternion.Euler(0, 0, 270+Mathf.Rad2Deg * Mathf.Atan2(rb.velocity.y, rb.velocity.x));
if (((Vector2)transform.forward + GetComponent<Rigidbody2D>().velocity.normalized).magnitude < 1.4)
tilt += 1f;
if (tilt != 0)
transform.Rotate (new Vector3 (0f, 0f, tilt * Time.deltaTime));
GetComponent<Rigidbody2D>().velocity -= Vector2.up * Time.deltaTime;
// Velocity
Vector2 vertvel = GetComponent<Rigidbody2D>().velocity - (Vector2)Vector3.ProjectOnPlane (transform.up, GetComponent<Rigidbody2D>().velocity);
fall = vertvel.magnitude;
GetComponent<Rigidbody2D>().velocity -= vertvel * Time.deltaTime;
GetComponent<Rigidbody2D>().velocity += vertvel.magnitude * (Vector2)transform.right * Time.deltaTime / 10;
// Drag
Vector2 forwardDrag = GetComponent<Rigidbody2D>().velocity - (Vector2)Vector3.ProjectOnPlane ((Vector2)transform.right, GetComponent<Rigidbody2D>().velocity);
GetComponent<Rigidbody2D>().AddForce (forwardDrag * forwardDrag.magnitude * Time.deltaTime / 1000);
airspeed = GetComponent<Rigidbody2D>().velocity.magnitude;
}
}

Categories

Resources