Unity trying to camera orbit controller - c#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camMouseLook : MonoBehaviour {
protected Transform XForm_camera;
protected Transform XForm_Parent;
protected Vector3 LocalRotation;
protected float CameraDistance = 10f;
public float MouseSensitivity = 4f;
public float ScrollSensitivity = 2f;
public float OrbitSpeed = 10f;
public float ScrollSpeed = 6f;
public bool CameraDisabled = false;
void Start () {
this.XForm_camera = this.transform;
this.XForm_Parent = this.transform.parent;
}
// Update is called once per frame
void LateUpdate () {
if (Input.GetKeyDown(KeyCode.LeftShift))
{
CameraDisabled = !CameraDisabled;
}
if (!CameraDisabled)
{
if(Input.GetAxis("Mouse X") != 0 || Input.GetAxis("Mouse Y") != 0)
{
LocalRotation.x += Input.GetAxis("Mouse X") * MouseSensitivity;
LocalRotation.y -= Input.GetAxis("Mouse Y") * MouseSensitivity;
LocalRotation.y = Mathf.Clamp(LocalRotation.y, 0f, 90f);
}
if(Input.GetAxis("Mouse ScrollWheel") != 0f)
{
float ScrollAmount = Input.GetAxis("Mouse ScrollWheel") *
ScrollSensitivity;
ScrollAmount *= (this.CameraDistance * 0.3f);
this.CameraDistance += ScrollAmount * -1f;
this.CameraDistance = Mathf.Clamp(this.CameraDistance, 1.5f, 100f);
}
}
Quaternion QT = Quaternion.Euler(LocalRotation.y, LocalRotation.x, 0);
this.XForm_Parent.rotation = Quaternion.Lerp(this.XForm_Parent.rotation, QT, Time.deltaTime * OrbitSpeed);
if (this.XForm_camera.localPosition.z != this.CameraDistance * -1f)
{
this.XForm_camera.localPosition = new Vector3(0f, 0f, Mathf.Lerp(this.XForm_camera.localPosition.z, this.CameraDistance * -1f, Time.deltaTime * ScrollSpeed));
}
}
}
I get an Object reference not set to an instance of an object error. I get this error on line "this.XForm_Parent.rotation=Quaternion.Lerp(this.XForm_Parent.rotation, QT, Time.deltaTime * OrbitSpeed);".
Hope someone can help me been struggling on this for a long time now.

You just need to attach your gameObject to the parent since you are telling
this.XForm_Parent = this.transform.parent and there is no parent attached to the gameObject ;)

Related

Camera gliitches when I walk on hill/slope in Unity3D

Good day,
I am making a first-person-view game. That works fine, but whenever I get on a hill/mountain etc. it starts freaking out. The player/camera starts rotating for no reason.
Note: I got some bits of code from external sources, so I don't fully comprehend every bit.
Here is the relevant code:
fpc script:
public float turnSpeed = 4.0f;
public float moveSpeed = 2.0f;
public float minTurnAngle = -90.0f;
public float maxTurnAngle = 90.0f;
private float rotX;
void Update()
{
MouseAiming();
KeyboardMovement();
}
void MouseAiming()
{
// get the mouse inputs
float y = Input.GetAxis("Mouse X") * turnSpeed;
rotX += Input.GetAxis("Mouse Y") * turnSpeed;
// clamp the vertical rotation
rotX = Mathf.Clamp(rotX, minTurnAngle, maxTurnAngle);
// rotate the camera
transform.eulerAngles = new Vector3(-rotX, transform.eulerAngles.y + y, 0);
}
void KeyboardMovement()
{
Vector3 dir = new Vector3(0, 0, 0);
dir.x = Input.GetAxis("Horizontal");
dir.z = Input.GetAxis("Vertical");
transform.Translate(dir * moveSpeed * Time.deltaTime);
}
MouseLookScript:
private PlayerInputActions controls;
[SerializeField] float mouseSensivity = 15f;
private float xRotation = 0f;
private Vector2 mouseLook;
private Transform playerBody;
private void Awake()
{
playerBody = transform.parent;
controls = new PlayerInputActions();
Cursor.lockState = CursorLockMode.Locked;
}
private void Update()
{
Look();
}
private void Look()
{
mouseLook = controls.Player.Look.ReadValue<Vector2>();
float mouseX = mouseLook.x * mouseSensivity * Time.deltaTime;
float mouseY = mouseLook.y * mouseSensivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector2.up, mouseX);
}
private void OnEnable()
{
controls.Enable();
}
private void OnDisable()
{
controls.Disable();
}
Hopefully someone will be able to help me!

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

Rotation smooth in editor but isn't in device

I have a 3D object that I want to rotate with mouse/finger swipe, so I made the script below.
The object's rotation looks smooth on editor, but when playing the game on real device (android), the rotation didn't follow the finger movement immediately, it takes some milliseconds to follow finger, it isn't smooth and the controls become hard and frustrating!
float sensitivity = 0.8f;
Vector2 firstPressPos;
Vector2 secondPressPos;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//save began touch 2d point
firstPressPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y);
}
if (Input.GetMouseButton(0))
{
//save ended touch 2d point
secondPressPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y);
if (firstPressPos != secondPressPos)
{
float RotX = Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
float RotY = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
transform.RotateAround(Vector3.up, RotX);
transform.RotateAround(Vector3.right, -RotY);
}
}
}
try this code
// Screen Touches
Vector2?[] oldTouchPositions = {
null,
null
};
// Rotation Speed
public float rotSpeed = 0.5f;
public void Update()
{
if (Input.touchCount == 0)
{
oldTouchPositions[0] = null;
oldTouchPositions[1] = null;
}
else if (Input.touchCount == 1)
{
if (oldTouchPositions[0] == null || oldTouchPositions[1] != null)
{
oldTouchPositions[0] = Input.GetTouch(0).position;
oldTouchPositions[1] = null;
}
else
{
Vector2 newTouchPosition = Input.GetTouch(0).position;
float distanceX = (oldTouchPositions[0] - newTouchPosition).Value.x;
float distanceY = (oldTouchPositions[0] - newTouchPosition).Value.y;
float rotX = distanceX * rotSpeed * Mathf.Deg2Rad;
float rotY = distanceY * rotSpeed * Mathf.Deg2Rad;
transform.Rotate(Vector3.up, rotX * 5, Space.Self);
transform.Rotate(Vector3.left, rotY * 5, Space.Self);
oldTouchPositions[0] = newTouchPosition;
}
}
else
{
if (oldTouchPositions[1] == null)
{
oldTouchPositions[0] = Input.GetTouch(0).position;
oldTouchPositions[1] = Input.GetTouch(1).position;
}
else
{
}
}
}
Here's a script I found a few years back that manipulates X axis spin with Mouse or Touches. It seems to work well with touches, but not as good with Mouse. Try it and let me know if it behaves a bit better. This one should adjust the spinning speed dynamically:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpinDrag : MonoBehaviour {
float f_lastX = 0.0f;
float f_difX = 0.5f;
float f_steps = 0.0f;
int i_direction = 1;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
f_difX = 0.0f;
}
else if (Input.GetMouseButton(0))
{
f_difX = Mathf.Abs(f_lastX - Input.GetAxis("Mouse X"));
if (f_lastX < Input.GetAxis("Mouse X"))
{
i_direction = -1;
transform.Rotate(Vector3.up, -f_difX);
}
if (f_lastX > Input.GetAxis("Mouse X"))
{
i_direction = 1;
transform.Rotate(Vector3.up, f_difX);
}
f_lastX = -Input.GetAxis("Mouse X");
}
else
{
if (f_difX > 0.5f) f_difX -= 0.05f;
if (f_difX < 0.5f) f_difX += 0.05f;
transform.Rotate(Vector3.up, f_difX * i_direction);
}
}
}

2D desktop control conversion to mobile controls c# & unityscript?

hope you all are doing good, friends i have a problem with my controls i build a 2d game, the game controls work fine for desktop but for mobile they are not working as expected, this is a script i am using for character moment. from mouse but instead of moving character this script make the camera follow it self or where the courser or finger presses and touches.
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 = 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 ()
{
// Make the rigid body not change rotation
if (rigidbody)
rigidbody.freezeRotation = true;
}
}
SECOND SCRIPT IS
private var motor : CharacterMotor;
function Awake () {
motor = GetComponent(CharacterMotor);
}
function Update () {
var directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, 0);
if (directionVector != Vector3.zero)
{
var directionLength = directionVector.magnitude;
directionVector = directionVector / directionLength;
directionLength = Mathf.Min(1, directionLength);
directionLength = directionLength * directionLength;
directionVector = directionVector * directionLength;
}
motor.inputMoveDirection = transform.rotation * directionVector;
motor.inputJump = Input.GetButton("Jump");
}

Categories

Resources