I am making a map game in unity. I want to drag the mouse on the map resulting in the player viewing different areas of the map (yes, like Hears of Iron IV). I have tried using the 'onDrag' method but I can not find the proper code for it. Can someone please link some documentation or required code for this method?
Thank you.
If you want to change camera position you can simply do it with this code:
public float dragSpeed = 2;
private Vector3 dragOrigin;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
dragOrigin = Input.mousePosition;
return;
}
if (!Input.GetMouseButton(0)) return;
Vector3 pos = Camera.main.ScreenToViewportPoint(dragOrigin - Input.mousePosition);
Vector3 move = new Vector3(pos.x * dragSpeed, 0, pos.y * dragSpeed);
transform.Translate(move, Space.World);
}
With this, you can start and do other things.
If you want to move the map instead of the camera you can also try :
private bool isDragging;
public void OnMouseDown()
{
isDragging = true;
}
public void OnMouseUp()
{
isDragging = false;
}
void Update()
{
if (isDragging) {
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
transform.Translate(mousePosition);
}
}
this work as Drag and Drop any 2d objects in unity.
the other answer does not work since the map should also move while button is held.. here is the fix
public float dragSpeed = 2;
private Vector3 dragOrigin;
private bool dragStarted = false;
if (Input.GetMouseButtonDown(1))
{
dragOrigin = Input.mousePosition;
dragStarted = true;
}
if (Input.GetMouseButtonUp(1))
{
dragStarted = false;
return;
}
if (dragStarted)
{
Vector3 pos = main_camera.ScreenToViewportPoint(dragOrigin - Input.mousePosition);
Vector3 move = new Vector3(pos.x * dragSpeed, 0, pos.y * dragSpeed);
main_camera.transform.Translate(move, Space.World);
}
this also assumes your camera is pointed downwards or facing north..
Related
I have this code for android touch input and want exact code and functionality with mouse pointer movement with persepective camera
public class InputManager : MonoBehaviour
{
private Touch touch;
private float speedModifier;
private void Start()
{
speedModifier = 0.01f;
}
private void Update()
{
if (Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved)
{
transform.position = new Vector3(
transform.position.x + touch.deltaPosition.x * speedModifier,
transform.position.y + touch.deltaPosition.y * speedModifier,
transform.position.z);
}
}
}
}
You can use
private Vector2 lastMousePosition;
private void OnMouseDown()
{
lastMousePosition = Input.mousePosition;
}
private void OnMouseDrag()
{
var deltaMousePosition = Input.mousePosition - lastMousePosition;
transform.position += deltaMousePosition * modifier;
lastMousePosition = Input.MousePosition;
}
Note though: This is fully depending on your display resolution as you directly apply the pixel space delta.
You might want to rather use a slightly different approach and use a mathematical plane and raycast to rather directly move in world space.
Something like e.g. this should do it
private Vector3 dragOffset;
private Plane dragPlane;
private Camera camera;
private void Awake ()
{
camera = Camera.main;
}
private void OnMouseDown()
{
var ray = camera.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out var hit) && hit.transform == transform)
{
dragOffset = hit.point - transform.position;
dragPlane = new Plane(-camera.forward, hit.point);
}
}
private void OnMouseDrag()
{
var ray = camera.ScreenPointToRay(Input.mousePosition);
if(dragPlane.Raycast(ray, out var distance))
{
transform.position = ray.GetPoint(distance) + dragOffset;
}
}
I am creating a build in Unity 2019.4.12f1 and need to drag an object with Right Mouse button.
My C# skills are very limited, so far but i try.
This scripts is my attempt to be able to rotate a gameobject by holding right mouse button down and dragging ingame.
But it is wrong.
Can anyone help me correct it?ยด
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mouseM : MonoBehaviour
{
bool dragging = false;
void Start()
{
if (Input.GetMouseButtonDown(1))
{
dragging = true;
}
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
yourOnMouseDownFunction();
dragging = true;
}
if (Input.GetMouseButtonUp(1))
{
yourOnMouseUpFunction();
dragging = false;
}
if (dragging)
{
yourOnMouseDragFunction();
}
}
}
I understood that You need to Drag Object in 3d World so Here is my Code just create new Script and attach to Object You Want to Drag it
Your Object that You need to Drag it should has a collider
using UnityEngine;
public class DragableObject : MonoBehaviour
{
private Vector3 mOffset;
private float mZCoord;
private void OnMouseDrag()
{
transform.position = GetMouseWorldPos() + mOffset;
}
private void OnMouseDown()
{
mZCoord = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
mOffset = transform.position - GetMouseWorldPos();
}
private Vector3 GetMouseWorldPos()
{
Vector3 mosePoint = Input.mousePosition;
mosePoint.z = mZCoord;
var result = Camera.main.ScreenToWorldPoint(mosePoint);
return result;
}
}
you can try it by adding it to sphere or cube and if you use custom shape you should insure that the collider is in suitable size or has a meshcollier
Demo
EDIT
using UnityEngine;
public class DragableObject : MonoBehaviour
{
private bool isMouseDragging;
private Vector3 screenPosition;
private Vector3 offset;
private GameObject target;
GameObject ReturnClickedObject(out RaycastHit hit)
{
GameObject targetObject = null;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray.origin, ray.direction * 10, out hit))
{
targetObject = hit.collider.gameObject;
}
return targetObject;
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
RaycastHit hitInfo;
target = ReturnClickedObject(out hitInfo);
if (target != null)
{
isMouseDragging = true;
Debug.Log("our target position :" + target.transform.position);
//Here we Convert world position to screen position.
screenPosition = Camera.main.WorldToScreenPoint(target.transform.position);
offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z));
}
}
if (Input.GetMouseButtonUp(1))
{
isMouseDragging = false;
}
if (isMouseDragging)
{
//tracking mouse position.
Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z);
//convert screen position to world position with offset changes.
Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset;
//It will update target gameobject's current postion.
target.transform.position = currentPosition;
}
}
}
You could try the Input.GetMouseButton method, this should return a value depending on if the button is held pressed.
This one works too, if someone needs in the future.
This is for rotate though.
Sorry, i dont know why it wont let me post as code, so i post an image.
enter image description here
I want to make a game, where you can throw items in 2D via drag and drop. This works fine, but the tracking of grabbing them is very bad. If I touch them in the top half the tracking won't or barely work.
Are there other methods to prevent this?
public class DropsBehaviour : MonoBehaviour {
//Declaring Variables
public int force = 10;
float maxSpeedPreset = 5;
float maxSpeed = 5;
float MaxThrowSpeed = 8;
GameManager gm;
Rigidbody rig;
Camera cam;
bool selected = false;
bool once = false;
void Start() {
gm = GameManager.FindMe();
rig = GetComponent<Rigidbody>();
cam = Camera.main;
}
void Update() {
if (selected) {
rig.AddForce((cam.ScreenToWorldPoint(Input.mousePosition) - transform.position) * force);
rig.velocity = Vector3.zero;
} else {
if (!once) {
maxSpeed = maxSpeedPreset * gm.gameSpeed;
rig.velocity = new Vector3(Mathf.Clamp(rig.velocity.x, -maxSpeed, maxSpeed), Mathf.Clamp(rig.velocity.y, -maxSpeed, maxSpeed), Mathf.Clamp(rig.velocity.z, -maxSpeed, maxSpeed));
} else {
maxSpeed = maxSpeedPreset;
rig.velocity = new Vector3(Mathf.Clamp(rig.velocity.x, -MaxThrowSpeed, MaxThrowSpeed), Mathf.Clamp(rig.velocity.y, -MaxThrowSpeed, MaxThrowSpeed), Mathf.Clamp(rig.velocity.z, -MaxThrowSpeed, MaxThrowSpeed));
}
}
}
void OnMouseDown() {
if (tag != "NoInteract") {
selected = true;
once = true;
}
}
void OnMouseUp() {
selected = false;
}
}
I see quite a few issues in the code snippet you posted that could cause stuttering.
First, if you are making something in 2D, it's recommended to use Rigidbody2D and Collider2D.
Then, you shouldn't edit a rigidbody's velocity by hand, as stated in the doc. That's what add force is made for.
When updating anything related to physics, you should do it in FixedUpdate, not Update.
I assume you also forgot to put " once = false " on the first pass ? Really not sure about this one.
I edited your script following the points stated before, while keeping the rigidbody 3D. I dind't tested it, but hopefully it will correct the weird drag behavior you're experiencing! (note that I removed the GameManager part since i can't know what it does)
public class DropsBehaviour : MonoBehaviour
{
public int force = 10;
private const float MaxSpeedPreset = 5;
private float _maxSpeed = 5;
private const float MaxThrowSpeed = 8;
private Rigidbody _rig;
private Camera _cam;
private bool _selected;
private bool _once;
private Vector3 _targetVelocity;
private void Start()
{
_rig = GetComponent<Rigidbody>();
_cam = Camera.main;
}
private void Update()
{
if (_selected) return;
if (!_once)
{
_maxSpeed = MaxSpeedPreset * 10;
_targetVelocity = new Vector3(Mathf.Clamp(_rig.velocity.x, -_maxSpeed, _maxSpeed),
Mathf.Clamp(_rig.velocity.y, -_maxSpeed, _maxSpeed),
Mathf.Clamp(_rig.velocity.z, -_maxSpeed, _maxSpeed));
}
else
{
_maxSpeed = MaxSpeedPreset;
_targetVelocity = new Vector3(Mathf.Clamp(_rig.velocity.x, -MaxThrowSpeed, MaxThrowSpeed),
Mathf.Clamp(_rig.velocity.y, -MaxThrowSpeed, MaxThrowSpeed),
Mathf.Clamp(_rig.velocity.z, -MaxThrowSpeed, MaxThrowSpeed));
_once = false; //Dunno if it's intended or not ?
}
}
private void FixedUpdate()
{
if (_selected)
{
_rig.AddForce((_cam.ScreenToWorldPoint(Input.mousePosition) - transform.position) * force);
_rig.velocity = Vector3.zero;
return;
}
var velocity = _rig.velocity;
var velocityChange = _targetVelocity - velocity;
_rig.AddForce(velocityChange, ForceMode.VelocityChange);
}
private void OnMouseDown()
{
if (CompareTag("NoInteract")) return;
_selected = true;
_once = true;
}
private void OnMouseUp()
{
_selected = false;
}
}
On a side note, I personnaly don't like tags, I would use a LayerMask instead since it's somewhat related to physics. I'd probably replace the OnMouse events with a Raycast too, that way you would have a lot more control on what is happening on the physic side.
I am making a 2d top down game where the player can rotate the camera around himself as he moves through the world.
Everything works fine when the player is moving around the world the camera follows him fine. if he standing still then the camera rotation also works very well. However as soon as I start to do both then there is a jittery in the camera that makes all other objects jitter besides the player.
Now in working with this problem I have found out that this could have to do with the fact that I use rigidbody2d.AddRelativeForce (so physics) to move the player and that his movements are checked in FixedUpdate.
https://forum.unity3d.com/threads/camera-jitter-problem.115224/ http://answers.unity3d.com/questions/381317/camera-rotation-jitterness-lookat.html
I have tried moving my camera rotation and the following scripts to LateUpdate, FixedUpdate, Update you name it. Nothing seems to work. I am sure that there is some sort of delay between movement of the camera and the rotation that is causing this. I am wondering if anyone has any feedback?
I have tried disabling Vsync, does not remove it entirely
I have tried interpolating and extrapolating the rigidbody and although there is a difference it does not remove it entirely. Ironically it seemd if I have it set to none, it works best.
Scripts:
To Follow character, script applied to a gameobject that has the camera as a child
public class FollowPlayer : MonoBehaviour {
public Transform lookAt;
public Spawner spawner;
private Transform trans;
public float cameraRot = 3;
private bool smooth = false;
private float smoothSpeed = 30f;
private Vector3 offset = new Vector3(0, 0, -6.5f);
//test
public bool changeUpdate;
private void Start()
{
trans = GetComponent<Transform>();
}
private void FixedUpdate()
{
CameraRotation();
}
private void LateUpdate()
{
following();
}
public void following()
{
Vector3 desiredPosition = lookAt.transform.position + offset;
if (smooth)
{
transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
}
else
{
transform.position = desiredPosition;
}
}
void CameraRotation()
{
if (Input.GetKey("q"))
{
transform.Rotate(0, 0, cameraRot);
}
if (Input.GetKey("e"))
{
transform.Rotate(0, 0, -cameraRot);
}
}
public void SetTarget(string e)
{
lookAt = GameObject.Find(e).GetComponent<Transform>();
}
}
The character Controller, script applied to the Player, is called in FixedUpdate
private void HandleMovement()
{
if (Input.GetKey("w"))
{
rigid.AddRelativeForce(Vector2.up * speed);
}
if (Input.GetKey("s"))
{
rigid.AddRelativeForce(Vector2.down * speed);
}
if (Input.GetKey("a"))
{
if (facingRight)
{
Flip();
}
rigid.AddRelativeForce(Vector2.left * speed);
}
if (Input.GetKey("d"))
{
if (!facingRight)
{
Flip();
}
rigid.AddRelativeForce(new Vector2(1,0) * speed);
}
}
Try to use Coroutines. I modified some of my scripts to be more familiar to Your code, tried it, and I didn't see any jittery. I hope that will help You.
Camera Class:
public class CameraController : MonoBehaviour {
[SerializeField]
Transform CameraRotator, Player;
[SerializeField]
float rotationSpeed = 10f;
float rotation;
bool rotating = true;
void Start()
{
StartCoroutine(RotatingCamera());
}
IEnumerator RotatingCamera()
{
while (rotating)
{
rotation = Input.GetAxis("HorizontalRotation");
CameraRotator.Rotate(Vector3.up * Time.deltaTime * rotation * rotationSpeed);
CameraRotator.position = Player.position;
yield return new WaitForFixedUpdate();
}
}
private void OnDestroy()
{
StopAllCoroutines();
}
}
Player Class:
public class PlayerMovement : MonoBehaviour {
[SerializeField]
float movementSpeed = 500f;
Vector3 movementVector;
Vector3 forward;
Vector3 right;
[SerializeField]
Transform CameraRotator;
Rigidbody playerRigidbody;
float inputHorizontal, inputVertical;
void Awake()
{
playerRigidbody = GetComponent<Rigidbody>();
StartCoroutine(Moving());
}
IEnumerator Moving()
{
while (true)
{
inputHorizontal = Input.GetAxis("Horizontal");
inputVertical = Input.GetAxis("Vertical");
forward = CameraRotator.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
Vector3 right = new Vector3(forward.z, 0, -forward.x);
movementVector = inputHorizontal * right + inputVertical * forward;
movementVector = movementVector.normalized * movementSpeed * Time.deltaTime;
playerRigidbody.AddForce(movementVector);
yield return new WaitForFixedUpdate();
}
}
}
I fixed this problem finally:
First I made my cameraRotation() and follow() into 1 function and gave it a better clearer name:
public void UpdateCameraPosition()
{
if (Input.GetKey("q"))
{
transform.Rotate(0, 0, cameraRot);
}
else if (Input.GetKey("e"))
{
transform.Rotate(0, 0, -cameraRot);
}
Vector3 desiredPosition = lookAt.transform.position + offset;
transform.position = desiredPosition;
}
I then called that function from the character controller straight after the handling of movement. Both calls (handleMovement & cameraPosition) in fixedUpdate.
void FixedUpdate()
{
HandleMovement();
cameraController.UpdateCameraPosition();
}
and the jittering was gone.
So it seems it was imply because there was a slight delay between the two calls as the previous posts I read had said. But I had failed to be able to properly Set them close enough together.
Hope this helps someone.
I am trying click on a GameObject and move it at the same rate as the mouse. I am able to get the Object to move, but I have to do some crazy modifications in order for it to not vanish off the screen.
Note: My ultimate goal will be to do this for mobile, but am starting with the mouse.
public class ItemController : MonoBehaviour {
private Vector3 startPos;
private bool ObjectMouseDown = false;
void Update()
{
Debug.Log(Input.mousePosition + new Vector3(0,0,15));
}
void OnMouseDown()
{
startPos = transform.position;
ObjectMouseDown = true;
}
void OnMouseDrag()
{
if (ObjectMouseDown == true)
{
transform.position = Vector3.MoveTowards(transform.position, Input.mousePosition + new Vector3(0, 0, 5), Time.deltaTime * 2f);
// transform.position = Vector3.MoveTowards(transform.position, endPosition, speed * Time.deltaTime);
}
}
void OnMouseUp()
{
ObjectMouseDown = false;
}
}
Notice how I have to add a z-value of 15, so that the object doesn't float up out of the screen.
Any help would be awesome.
Input.mousePosition return the absolute pixel position on the screen and not world position. You need to use Camera.ScreenToWorldPoint something like this
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.position.x, Input.position.y, 15);
transform.position = mouseWorldPos;
You can read more here https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html