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");
}
Related
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!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[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;
}
}
I use a script for rotation of the camera with the mouse and I want to transform it for the touch . I want my camera to rotate just when I touch the screen . The game has a first player controller . Please help me to make it for touchscreen
Get the first Touch, then use touch.deltaPosition to find how much the touch has moved since the last update. Then, you can scale with screen size and sensitivity.
void Update()
{
if(Input.touchCount > 0) {
Touch touch = Input.GetTouch(0);
float turnAngleChange = (touch.deltaPosition.x / Screen.width) * sensitivityX;
float pitchAngleChange = (touch.deltaPosition.y / Screen.height) * sensitivityY;
// Handle any pitch rotation
if (axes == RotationAxes.MouseXAndY || axes == RotationAxes.MouseY) {
rotationY = Mathf.Clamp(rotationY+pitchAngleChange, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0f));
}
// Handle any turn rotation
if (axes == RotationAxes.MouseXAndY || axes == RotationAxes.MouseX) {
transform.Rotate(0f, turnAngleChange , 0f);
}
}
}
As a sidenote, it can be confusing to call pitch rotations rotationY even though they are actually rotations along the x axis, and vice versa.
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);
}
}
}
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 ;)
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