I want control the transform with mouse just for Y axis as it is moving on X axis by it self.
I use Vector2.MoveTowards to move it on X axis.
The transform must be moved by any touch and drag on the screen. So I wrote my codes in the Update function
My Codes :
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public Camera playerCamera;
public float speed = 12.0F;
private Vector3 moveDirection = Vector3.zero,Point,last;
void Start()
{
Point = transform.position;
last = transform.position;
if (playerCamera == null)
{
playerCamera = Camera.main;
}
playerCamera.transparencySortMode = TransparencySortMode.Orthographic;
}
void Update(){
if(Input.GetMouseButtonUp(0))
Point = last;
moveDirection.x = transform.position.x+speed;
moveDirection.y = transform.position.y;
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
last = ray.GetPoint (0);
transform.position = new Vector2 (transform.position.x, last.y - Point.y);
}
else
transform.position = Vector2.MoveTowards( transform.position,moveDirection,speed*Time.deltaTime);
//moveDirection.y -= 20.0f * Time.smoothDeltaTime;
//After we move, adjust the camera to follow the player
playerCamera.transform.position = new Vector3(transform.position.x, playerCamera.transform.position.y , playerCamera.transform.position.z);
}
}
How can I solve it?
Related
I make game with fps , when I rotate the camera the joystick doesn't work properly. I have a fixed Joystick , when I try to move by rotation anything in movement change . Do I need to change the joystick ? or do I need to change something in the script for the camera rotation ? When I start the game on the mobile , the rotation affects the joystick . When I move the joystick forward and do some rotation , forward becomes backward , left right , if I move right the rotation , right becomes backward , etc . what can I do
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 (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);
}
}
void Start()
{
//if(!networkView.isMine)
//enabled = false;
// Make the rigid body not change rotation
//if (rigidbody)
//rigidbody.freezeRotation = true;
}
}
}
I'm starting out with a small shooting game but I have a problem with my character. The arms have to rotate 360º but the body only right or left (depending on where the rotation of the arms by the mouse).
What I got so far is what you see in the video below but I have two big problems and with the help of tutorials.
I was able to rotate and flip my arms but not the body.
Also, when it fires to the right the bullets exit correctly from the firepoint that I created but after the arms flip to the left the bullets (and the weapon fire) are no longer aligned.
Is this approach that I have tried is not the best for this problem?
I appreciate your help.
Game link: https://vimeo.com/310853740
Here my arm rotation script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArmRotation : MonoBehaviour
{
SpriteRenderer spriteRend;
void Awake()
{
spriteRend = GetComponent<SpriteRenderer>();
}
void Update()
{
AimArmAtMouse();
}
void AimArmAtMouse()
{
Vector2 mousePosition = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 armToMouse = mousePosition - (Vector2)transform.position;
float rotationZ = Vector2.SignedAngle(transform.right, armToMouse);
transform.Rotate(0f, 0f, rotationZ);
FlipArm(Vector2.SignedAngle(transform.right, Vector2.right));
}
void FlipArm(float rotation)
{
if (rotation < -90f || rotation > 90f)
{
spriteRend.flipY = true;
}
else
{
spriteRend.flipY = false;
}
}
}
It's because you don't flip the firepoint when you flip the sprite. I re-wrote you script to include a reference to the firepoint. I also added a 'FlipFirePoint' function which gets called by your 'FlipArm' function. It should fix your alignment issue.
using UnityEngine;
public class ArmRotation : MonoBehaviour
{
SpriteRenderer spriteRend;
public Transform firePoint;
void Awake()
{
spriteRend = GetComponent<SpriteRenderer>();
}
void Update()
{
AimArmAtMouse();
}
void AimArmAtMouse()
{
Vector2 mousePosition = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 armToMouse = mousePosition - (Vector2)transform.position;
float rotationZ = Vector2.SignedAngle(transform.right, armToMouse);
transform.Rotate(0f, 0f, rotationZ);
FlipArm(Vector2.SignedAngle(transform.right, Vector2.right));
}
void FlipArm(float rotation)
{
if (rotation < -90f || rotation > 90f)
{
spriteRend.flipY = true;
FlipFirePoint(true);
}
else
{
spriteRend.flipY = false;
FlipFirePoint(false);
}
}
void FlipFirePoint(bool flip)
{
var pos = firePoint.localPosition;
pos.x = Mathf.Abs(pos.x) * (flip ? -1 : 1);
firePoint.localPosition = pos;
}
}
#Sean, I separated the main_body from the arms and made a new script just for body rotation but now it happens to me this:
My test char
The code:
void Update()
{
Flip();
}
void Flip()
{
Vector3 theScale = transform.localScale;
Vector3 pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
float WorldXPos = Camera.main.ScreenToWorldPoint(pos).x;
if (WorldXPos > gameObject.transform.position.x)
{
theScale.x = 1;
transform.localScale = theScale;
}
else
{
theScale.x = -1;
transform.localScale = theScale;
}
}}
Almost there but not yet i need😁
I am trying to move an airplane yoke in the vertical axis. I am using the mouse pointer to move yoke in vertical axis up and down and clamped the value. When I run the script the yoke is positioned some ever and not moving up and down. The yoke is not moving up and down. How to move yoke up and down as shown in the image using below code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace plane
{
public class IP_AirplaneThrottle_Physical : MonoBehaviour
{
#region Variables
public float maxZOffset = -0.5f;
public float sensitivity = 0.001f;
public float smoothSpeed = 8f;
public bool isHitting = false;
public float wantedDelta;
private Vector3 startPos;
private Vector3 wantedPos;
private Vector2 lastMousePosition;
#endregion
#region Builtin Methods
// Use this for initialization
void Start()
{
//Get the lever starting position
startPos = transform.position;
}
// Update is called once per frame
void Update()
{
HandleRaycast();
HandleInteraction();
}
#endregion
#region Custom Methods
void HandleRaycast()
{
//Build a ray so we can see if we are hitting the lever
Ray curRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
//Do our Raycast into the scene
if(Physics.Raycast(curRay, out hit, 1000f))
{
if(hit.transform.GetInstanceID() == this.transform.GetInstanceID())
{
Debug.Log("Hitting the Lever!");
if(Input.GetMouseButtonDown(0))
{
//We are hitting so get the start mouse position
isHitting = true;
lastMousePosition = Input.mousePosition;
print ("123");
}
}
}
//If we let go of the left mouse button then stop everything
if(isHitting && Input.GetMouseButton(0) == false)
{
isHitting = false;
}
}
void HandleInteraction()
{
if(isHitting)
{
//Calculate the delta for Z offset
wantedDelta = (lastMousePosition.y - Input.mousePosition.y) * Time.deltaTime * sensitivity;
startPos.z += wantedDelta;
//make sure we dont go to far
startPos.z = Mathf.Clamp(startPos.z, maxZOffset, 0f);
wantedPos = startPos;
//Get the New Mouse Position every frame while we are holding
lastMousePosition = Input.mousePosition;
}
else
{
//Clear out the Delta value
wantedDelta = 0f;
}
//Move the lever
transform.position = Vector3.Lerp(transform.position, wantedPos, Time.deltaTime * smoothSpeed);
}
#endregion
}
}
I am using a map bigger than the screen I viewing. Therefore I need to be able to pan around that map. I am having a problem with clamping the camera and the map. I want to be able to use the demension of the image as the width and height of the clamp. The problem is the units.
The image is 2144 x 1708
The camera transposition is in single digits (14 x 7) or something like that.
All of the code I am using is below.
private Vector3 mouseOrigin; // Position of cursor when mouse dragging starts
private bool isPanning; // Is the camera being panned?
public bool useBoundary = true;
public Vector2 boundaryMin;
public Vector2 boundaryMax;
public Image map;
private void Start()
{
Camera cam = Camera.main;
float mapRatio = map.rectTransform.rect.width / map.rectTransform.rect.height;
float mapScreenHeight = (1.5f * cam.orthographicSize);
float mapScreenWidth = (3f * mapScreenHeight) * cam.aspect;
boundaryMin = new Vector2(0, 1);
boundaryMax = new Vector2(map.rectTransform.rect.width, map.rectTransform.rect.height);
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
mouseOrigin = Input.mousePosition;
isPanning = true;
}
// Disable movements on button release
if (!Input.GetMouseButton(0))
isPanning = false;
if (isPanning)
{
Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - mouseOrigin);
Vector3 move = new Vector3(pos.x * panSpeed, pos.y * panSpeed, 0);
transform.Translate(move, Space.Self);
BoundaryCheck();
}
}
private void BoundaryCheck()
{
if (!useBoundary)
return;
Vector3 newPos = transform.position;
newPos.x = Mathf.Clamp(newPos.x, boundaryMin.x, boundaryMax.x);
newPos.y = Mathf.Clamp(newPos.y, boundaryMin.y, boundaryMax.y);
transform.position = newPos;
}
}
Any help would be greatly appreciated.
You can do this using Unity UI - Scroll Rect.
Check out Unity UI - Scroll Rect - Introduction
In my opinion you should need to use below script for camera panning, zooming and rotating. You can off any undesirable function. Now according to your question you have to restrict the movement(according to your image border). simply you can restrict the camera movements on differet axis according to your limitations. You should place cubes into the borders of the map and use their positions as the limit of camera movement and panning etc.
using UnityEngine;
using System.Collections;
public class CamMovementManager : MonoBehaviour
{
#region Vars
public float turnSpeed = 1.0f; // Speed of camera turning when mouse moves in along an axis
public float panSpeed = 4.0f; // Speed of the camera when being panned
public float zoomSpeed = 4.0f; // Speed of the camera going back and forth
private Vector3 mouseOrigin; // Position of cursor when mouse dragging starts
private bool isPanning; // Is the camera being panned?
private bool isRotating; // Is the camera being rotated?
private bool isZooming; // Is the camera zooming?
private float pannPosLimit = 300f;
private int fovMin = 15;
private int fovMax = 90;
#endregion Vars
#region UnityEvents
void Update()
{
// Get the left mouse button
if (Input.GetMouseButtonDown(0))
{
// Get mouse origin
mouseOrigin = Input.mousePosition;
isRotating = true;
}
// Get the right mouse button
if (Input.GetMouseButtonDown(1))
{
// Get mouse origin
mouseOrigin = Input.mousePosition;
isPanning = true;
}
// Get the middle mouse button
if (Input.GetMouseButtonDown(2))
{
// Get mouse origin
//mouseOrigin = Input.mousePosition;
//isZooming = true;
}
//changing fov on mouse scroll to zoomIn/out
float fov = Camera.main.fieldOfView;
fov += Input.GetAxis("Mouse ScrollWheel") * 10f;
fov = Mathf.Clamp(fov, fovMin, fovMax);
Camera.main.fieldOfView = fov;//*/
// Disable movements on button release
if (!Input.GetMouseButton(0)) isRotating = false;
if (!Input.GetMouseButton(1)) isPanning = false;
if (!Input.GetMouseButton(2)) isZooming = false;
// Rotate camera along X and Y axis
if (isRotating)
{
Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - mouseOrigin);
//Debug.Log("rotate pos : " + pos);
transform.RotateAround(transform.position, transform.right, -pos.y * turnSpeed);
transform.RotateAround(transform.position, Vector3.up, pos.x * turnSpeed);
}
// Move the camera on it's XY plane
if (isPanning)
{
if (Input.mousePosition.y > pannPosLimit)
{
Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - mouseOrigin);
Vector3 move = new Vector3(pos.x * panSpeed, pos.y * panSpeed, 0);
transform.Translate(move, Space.Self);
}
}
// Move the camera linearly along Z axis
if (isZooming)
{
Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - mouseOrigin);
Vector3 move = pos.y * zoomSpeed * transform.forward;
transform.Translate(move, Space.World);
}
}
#endregion
#region CustomMethods
public void CamRotating()
{
Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - mouseOrigin);
transform.RotateAround(transform.position, transform.right, -pos.y * turnSpeed);
transform.RotateAround(transform.position, Vector3.up, pos.x * turnSpeed);
}
public void CamPanning()
{
Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - mouseOrigin);
Vector3 move = new Vector3(pos.x * panSpeed, pos.y * panSpeed, 0);
transform.Translate(move, Space.Self);
}
public void CamZooming()
{
Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - mouseOrigin);
Vector3 move = pos.y * zoomSpeed * transform.forward;
transform.Translate(move, Space.World);
}
#endregion CustomMethods
}
What I mean in my question is that how to make your player rotate automatically when I move my mouse left for example and my whole characters body will rotate and limit its rotation back to a 2D view.
Similar to the game "Rochard" if you guys know it. But I'm having trouble how to figure it out.
This is my Code:
#pragma strict
var spinx : int = 0;
var spiny : int = 0;
var spinz : int = 0;
function Update () {
transform.Rotate(spinx, spiny, spinz);
}
The following script should rotate your object according to mouse position,
using UnityEngine;
using System.Collections;
public class RotateClass : MonoBehaviour {
public float horizontalSpeed = 2.0F;
public float verticalSpeed = 2.0F;
void Update() {
float h = horizontalSpeed * Input.GetAxis("Mouse X");
float v = verticalSpeed * Input.GetAxis("Mouse Y");
transform.Rotate(v, h, 0);
}
}
First, I am really sorry to write it in C#. But I hope it can help you. This script is attached to player gameobject.
private Vector3 MousePositionViewport = Vector3.zero;
private Quaternion DesiredRotation = new Quaternion();
private float RotationSpeed = 15;
void Update () {
MousePositionViewport = Camera.main.ScreenToViewportPoint (Input.mousePosition);
if (MousePositionViewport.x >= 0.6f) {
DesiredRotation = Quaternion.Euler (0, 90, 0);
} else if(MousePositionViewport.x < 0.6f && MousePositionViewport.x > 0.4f){
DesiredRotation = Quaternion.Euler (0, 270, 0);
}else {
DesiredRotation = Quaternion.Euler (0, 180, 0);
}
transform.rotation = Quaternion.Lerp (transform.rotation, DesiredRotation, Time.deltaTime*RotationSpeed);
}
this script should rotate your object acccording to mouse position
using UnityEngine;
using System.Collections;
public class MouseLook : MonoBehaviour {
void Update () {
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.z, 10);
Vector3 lookPos = Camera.main.ScreenToWorldPoint(mousePos);
lookPos = lookPos - transform.position;
float angle = Mathf.Atan2(lookPos.z, lookPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
You could import the standard player controls package from unity itself and edit the first person controller to your likings. This is what I tend to do when I want a control in my game that can do what you desire.