How to make a boundary in 2d - c#

I an trying to keep my charecter inside boundaries but I was only able to get it to work for the side walls and not the bottem and top walls. Here is my code for moving and the boundaries.
{
public float verticalInput;
public float horizontalInput;
public float speed = 10.0f;
public float Xrange = 9.5f;
public float Yrange = 4.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed);
verticalInput = Input.GetAxis("Vertical");
transform.Translate(Vector3.up * verticalInput * Time.deltaTime * speed);
if (transform.position.x < -Xrange)
{
transform.position = new Vector3(-Xrange, transform.position.y, transform.position.z);
}
if (transform.position.x > Xrange)
{
transform.position = new Vector3(Xrange, transform.position.y, transform.position.z);
}
if (transform.position.y < -Yrange)
{
transform.position = new Vector3(-Yrange, transform.position.x, transform.position.z);
}
if (transform.position.y > Yrange)
{
transform.position = new Vector3(Yrange, transform.position.x, transform.position.z);
} ```

Related

I keep getting the error "Assets\ThirdPersonMovement.cs(49,30): error CS0117: 'Input' does not contain a definition for 'getAxis'"

Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 6f;
public float turnSmoothTime = 0.1f;
public Transform cam;
private float verticalVelocity;
private float gravity = 14.0f;
private float jumpForce = 10.0f;
float turnSmoothVelocity;
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
if (controller.isGrounded)
{
verticalVelocity = -gravity * Time.deltaTime;
if (Input.getKeyDown(KeyCode.Space))
{
verticalVelocity = jumpForce;
}
}
else
{
verticalVelocity -= gravity * Time.deltaTime;
}
Vector3 moveVector = Vector3.zero;
moveVector.x = Input.getAxis("Horizontal") * speed;
moveVector.y = verticalVelocity;
moveVector.z = Input.getAxis("Vertical") * speed;
controller.Move(moveVector * Time.deltaTime);
}
}
It has been giving me this error for a couple weeks and I can't figure it out.
I've tried seeing if anybody else has had any issues and looking back at how others have overcome this issue, but nothing seems to be working.
C# is case-sensitive.
moveVector.x = Input.GetAxis("Horizontal") * speed;
moveVector.y = verticalVelocity;
moveVector.z = Input.GetAxis("Vertical") * speed;

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

Why do objects stutter while I move and the camera is rotating?

I have began developing an fps script and followed a tutorial to help with the script. Everything works great now but the only issue is any objects in the view seem to stutter whenever the player is moving and rotating at the same time.
The script for the player's movement and camera rotation is below.
Can anybody point me in the right direction?
Thank you.
{
public Transform cam;
public Rigidbody rb;
public float camRotationSpeed = 5f;
public float camMinimumY = -60f;
public float camMaximumY = 75f;
public float rotationSmoothSpeed = 10f;
public float walkSpeed = 9f;
public float runSpeed = 14f;
public float maxSpeed = 20f;
public float jumpPower = 30f;
public float extraGravity = 45;
float bodyRotationX;
float camRotationY;
Vector3 directionIntentX;
Vector3 directionIntentY;
float speed;
public bool grounded;
void Update()
{
LookRotation();
Movement();
ExtraGravity();
GroundCheck();
if(grounded && Input.GetButtonDown("Jump"))
{
Jump();
}
}
void LookRotation()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
bodyRotationX += Input.GetAxis("Mouse X") * camRotationSpeed;
camRotationY += Input.GetAxis("Mouse Y") * camRotationSpeed;
camRotationY = Mathf.Clamp(camRotationY, camMinimumY, camMaximumY);
Quaternion camTargetRotation = Quaternion.Euler(-camRotationY, 0, 0);
Quaternion bodyTargetRotation = Quaternion.Euler(0, bodyRotationX, 0);
transform.rotation = Quaternion.Lerp(transform.rotation, bodyTargetRotation, Time.deltaTime * rotationSmoothSpeed);
cam.localRotation = Quaternion.Lerp(cam.localRotation, camTargetRotation, Time.deltaTime * rotationSmoothSpeed);
}
void Movement()
{
directionIntentX = cam.right;
directionIntentX.y = 0;
directionIntentX.Normalize();
directionIntentY = cam.forward;
directionIntentY.y = 0;
directionIntentY.Normalize();
rb.velocity = directionIntentY * Input.GetAxis("Vertical") * speed + directionIntentX * Input.GetAxis("Horizontal") * speed + Vector3.up * rb.velocity.y;
rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
if (Input.GetKey(KeyCode.LeftShift))
{
speed = runSpeed;
}
if (!Input.GetKey(KeyCode.LeftShift))
{
speed = walkSpeed;
}
}
void ExtraGravity()
{
rb.AddForce(Vector3.down * extraGravity);
}
void GroundCheck()
{
RaycastHit groundHit;
grounded = Physics.Raycast(transform.position, -transform.up, out groundHit, 1.25f);
}
void Jump()
{
rb.AddForce(Vector3.up * jumpPower, ForceMode.Impulse);
}
}
This probably happens because the frame needs to update the camera rotation and the player position at the same time. i would suggest doing the rotation of the camera in fixed update. because this will run at the end of each frame.
like this:
void FixedUpdate()
{
LookRotation();
}
another thing i would suggest is to move the player while the groundcheck is being ran, because if you do it seperately i can see a bug coming up when the player moves faster then the code can run or something. so a tip would be or to run it inside the movement method, or call the method while you are calling the movement method.
this:
void Movement()
{
directionIntentX = cam.right;
directionIntentX.y = 0;
directionIntentX.Normalize();
directionIntentY = cam.forward;
directionIntentY.y = 0;
directionIntentY.Normalize();
rb.velocity = directionIntentY * Input.GetAxis("Vertical") * speed + directionIntentX * Input.GetAxis("Horizontal") * speed + Vector3.up * rb.velocity.y;
rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
if (Input.GetKey(KeyCode.LeftShift))
{
speed = runSpeed;
}
if (!Input.GetKey(KeyCode.LeftShift))
{
speed = walkSpeed;
}
GroundCheck();
}
or litteraly copy and paste the code within your movement method.

Player starts to jump on planet that has it's own gravity when moving south

So I have a planet that has its own gravity and I can move around the top just fine but when I go towards the south the player starts to jump up and down for some reason and I'm not sure as to why any thoughts on how I can fix it?
Video of problem
Planet Gravity
void OnTriggerStay(Collider other)
{
if (other.gameObject.GetComponent<Rigidbody>())
{
Vector3 difference = this.gameObject.transform.position - other.gameObject.transform.position;
float dist = difference.magnitude;
Vector3 gravityDirection = difference.normalized;
Vector3 gravityVector = (gravityDirection * gravity) / (dist * dist);
other.gameObject.GetComponent<Rigidbody>().AddForce(gravityVector, ForceMode.Acceleration);
}
}
Movement
void Update ()
{
////Defaults to the left Stick
float hAxis = Input.GetAxis("Horizontal");
float vAxis = Input.GetAxis("Vertical");
Vector3 NextDir = new Vector3(hAxis, 0, vAxis);
float deadzone = 0.25f;
//Vector2 stickInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
if (NextDir.magnitude < deadzone)
{
NextDir = Vector3.zero;
}
else
{
NextDir = NextDir.normalized * ((NextDir.magnitude - deadzone) / (1 - deadzone));
transform.rotation = Quaternion.LookRotation(NextDir);
transform.Translate(NextDir.x * Time.deltaTime * 5, NextDir.y * Time.deltaTime * 5, NextDir.z * Time.deltaTime * 5, Space.Self);
}
}
}
Player Orientation Script
void LateUpdate()
{
Vector3 dir = planet.transform.position - transform.position;
dir.Normalize();
RaycastHit hit;
if (Physics.Raycast(transform.position, dir * 100, out hit))
{
transform.localRotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
}
}

Make player move forward,right,left and backwards based on camera angle

So far I have a player who moved forward left right and backwards, however how I have it set up it's forward as in forward on the grid, not forward where my player is looking. I have the camera set as FPS, with it following the player around. Now I want to have the player be able to look with my MouseLook script (works already) but based on that I want forward to be wherever the player is looking, not the primitive version I have. I'll post code below to let you know what I am talking about, ANY help is appreciated.
Player Script (movement)
void Update () {
if(Input.GetKey (moveU))
{
SetTransformZ((transform.position.z) + playerSpeed);
}
if(Input.GetKey (moveD))
{
SetTransformZ((transform.position.z) - playerSpeed);
}
if(Input.GetKey (moveL))
{
SetTransformX((transform.position.x) - playerSpeed);
}
if(Input.GetKey (moveR))
{
SetTransformX((transform.position.x) + playerSpeed);
}
else
{
rigidbody.angularVelocity = Vector3.zero;
}
}
void SetTransformX(float n)
{
transform.position = new Vector3(n, transform.position.y, transform.position.z);
}
void SetTransformZ(float n)
{
transform.position = new Vector3(transform.position.x, transform.position.y, n);
}
MouseLook script (attached to Main Camera in Unity, this works witht he player so it goes whereever my mouse is looking, but the movement is off since my code to move is very primitive)
[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;
}
Okay, so you want your player to move forward, left, right, back relative to where they are looking, as I understand it.
First, make sure that transform.forward is the right direction for your player. in the editor you can select your player gameObject and see if the blue arrow faces the same direction as your player. If not, check out this thread on the unity answers forum to see how to change it.
Here are some functions to put into your player controller script to move relative to player rotation rather than position.
(Note: check out Time.deltaTime)
private void moveForward(float speed) {
transform.localPosition += transform.forward * speed * Time.deltaTime;
}
private void moveBack(float speed) {
transform.localPosition -= transform.forward * speed * Time.deltaTime;
}
private void moveRight(float speed) {
transform.localPosition += transform.right * speed * Time.deltaTime;
}
private void moveLeft(float speed) {
transform.localPosition -= transform.right * speed * Time.deltaTime;
}
Note: transform.position vs transform.localPosition

Categories

Resources