ScreenToWorld point on 2d scale without affecting the Z position - c#

I'm creating a draggable item but whenever I drag it's z position would become 47 and I wanted it to retain to 0.
using UnityEngine;
using UnityEngine.EventSystems;
public class draggableItem : MonoBehaviour, IBeginDragHandler, IDragHandler , IEndDragHandler
{
Transform setParentAferDrag;
public void OnBeginDrag(PointerEventData eventData)
{
setParentAferDrag = transform.parent;
transform.SetParent(transform.root);
transform.SetAsLastSibling();
}
public void OnDrag(PointerEventData eventData)
{
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = mousePos;
}
public void OnEndDrag(PointerEventData eventData)
{
transform.SetParent(setParentAferDrag);
}
}

Related

Camera rotate by movement joystick

I have first person shooter. It's work when I rotate the camera at first (right part of the screen) and then use joystick for movement (left part of the screen). But if I use joystick for movement and then rotate the camera - player move and camera rotate by joystick, not by camera rotation zone. How to fix it?
using UnityEngine;
using UnityEngine.EventSystems;
public class FixedTouchField : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
[HideInInspector]
public Vector2 TouchDist;
[HideInInspector]
public Vector2 PointerOld;
[HideInInspector]
protected int PointerId;
[HideInInspector]
public bool Pressed;
void Start()
{
}
void Update()
{
if (Pressed)
{
if (PointerId >= 0 && PointerId < Input.touches.Length)
{
TouchDist = Input.touches[PointerId].position - PointerOld;
PointerOld = Input.touches[PointerId].position;
}
else
{
TouchDist = new Vector2(Input.mousePosition.x, Input.mousePosition.y) - PointerOld;
PointerOld = Input.mousePosition;
}
}
else
{
TouchDist = new Vector2();
}
}
public void OnPointerDown(PointerEventData eventData)
{
Pressed = true;
//PointerId = eventData.pointerId;
//PointerOld = eventData.position;
PointerOld = Input.touches[PointerId].position;
}
public void OnPointerUp(PointerEventData eventData)
{
Pressed = false;
}
}

Unity C# Dragged item positions itself a few centimeters above mouse mosition

So I have a script (For drag and drop inventory system) that was working fine yesterday, but this morning the Items being dragged no longer followed the mouse pointer at the crusors position but instead followed it with a at a distance. So upon clicking the item, nothing happened, once i start dragging the item x,y values just changed and placed itself a few centimeters above the crusor whilst still following the crusor.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public static GameObject itemBeingDragged;
Vector2 startPosition;
Transform startParent;
public void OnBeginDrag ( PointerEventData eventData)
{
itemBeingDragged = gameObject;
startPosition = transform.position;
startParent = transform.parent;
GetComponent<CanvasGroup>().blocksRaycasts = false;
}
public void OnDrag (PointerEventData eventData)
{
transform.position = Input.mousePosition;
}
public void OnEndDrag (PointerEventData eventData)
{
itemBeingDragged = null;
GetComponent<CanvasGroup>().blocksRaycasts = true;
if (transform.parent == startParent)
{
transform.position = startPosition;
}
}
}
ยดยดยด
When you drag an item, the mouse can be anywhere inside the item. You should therefore calculate the delta between the mouse position and the position of the dragged item. You can then add this delta in the OnDrag() functions when setting a new position.
Vector3 delta;
public void OnBeginDrag(PointerEventData eventData)
{
itemBeingDragged = gameObject;
delta = itemBeingDragged.transform.position -
new Vector3(eventData.pressPosition.x, eventData.pressPosition.y, 0);
// ....
}
...
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition + delta;
}
Note that we should not use the Input.mousePosition in the OnBeginDrag() since the drag operation starts first after the mouse has moved a bit. We could of course calculate the delta as soon as the mouse button was pressed, and then we can use the Input.mousePosition. But, since you use the OnBeginDrag() we use the event's pressPosition which is the mousePosition when pressed.

Unity - character starts to fly up when there should be gravity

I am developing a 2D platform game, where the character is a ball and should be able to move right and left, and to jump. It now does all that, but for some reason which i do not understand (as i am complitely new to Unity) sometimes it flies up like if the gravity was negative.
Here is the code of my first script Move2D:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move2D : MonoBehaviour
{
public float moveSpeed = 5f;
public bool isGrounded = false;
[SerializeField] private Rigidbody2D rigidbody;
private Vector2 currentMoveDirection;
private void Awake()
{
rigidbody = GetComponent<Rigidbody2D>();
currentMoveDirection = Vector2.zero;
}
public void Jump()
{
if (isGrounded)
{
rigidbody.AddForce(new Vector3(0f, 5f), ForceMode2D.Impulse);
}
}
private void FixedUpdate()
{
rigidbody.velocity = (currentMoveDirection + new Vector2(0f, rigidbody.velocity.y)).normalized * moveSpeed;
}
public void TriggerMoveLeft()
{
currentMoveDirection += Vector2.left;
}
public void StopMoveLeft()
{
currentMoveDirection -= Vector2.left;
}
public void TriggerMoveRight()
{
currentMoveDirection += Vector2.right;
}
public void StopMoveRight()
{
currentMoveDirection -= Vector2.right;
}
}
And this is the code of the second script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ContinuesButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
[SerializeField] private Button targetButton;
[SerializeField] private Move2D playerMovement;
[SerializeField] private bool movesLeft;
private readonly bool isHover;
private void Awake()
{
if (!targetButton) targetButton = GetComponent<Button>();
}
public void OnPointerDown(PointerEventData eventData)
{
if (movesLeft)
{
playerMovement.TriggerMoveLeft();
} else
{
playerMovement.TriggerMoveRight();
}
}
public void OnPointerUp(PointerEventData eventData)
{
if (movesLeft)
{
playerMovement.StopMoveLeft();
} else
{
playerMovement.StopMoveRight();
}
}
}
I noticed that the ball starts to fly up as soon as the movement controller or some collider makes it go up a bit. For example when i make it jump, it just keeps going up, or when in the game i try to make it "walk" up a hill, it immediately starts flying up.
Any help or information is really appreciated, I really do not see the problem.
The issue I lies in normalized. This might unexpectedly increase the Y velocity. Especially in cases when you set the X velocity to 0 the Y component is taken into account to much.
I guess you should rather use something like
currentDirection * moveSpeed + Vector2.up * rigidbody.velocity.y;
In order to simply keep the current Y velocity.
Also be careful with these currentDirection += ...! I would suggest rather use single methods and use fixed values like e.g.
public void DoMove(bool right)
{
currentDirection = (right ? 1 : -1) * Vector2.right;
}
public void StopMove()
{
currentDirection = Vector2.zero;
}
And then rather call them like
public void OnPointerDown(PointerEventData eventData)
{
playerMovement.DoMove(!movesLeft);
}
public void OnPointerUp(PointerEventData eventData)
{
playerMovement.StopMove();
}

I want to move 2d object only horizontally by touch in Unity

I implemented a touch drag.
But I can not move only horizontally.
I would expect to limit it to if, but I do not know what to do after that.
Here is my code.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;
public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public void OnBeginDrag (PointerEventData eventData)
{
Debug.Log ("OnBeginDrag");
}
public void OnDrag (PointerEventData eventData)
{
Debug.Log ("OnBeginDrag");
//this.transform.position = eventData.position;
GetComponent<Transform> ().position = eventData.position;
}
public void OnEndDrag (PointerEventData evnetData)
{
Debug.Log ("OnEndDrag");
}
}
You don't need to call GetComponent for transform.
If the code you were using works and you just want horizontal drag, something like this should work.
var currentPos = transform.position;
transform.position = new Vector3(eventData.position.x, currentPos.y, currentPos.z);

Game Object does not retain its original position when left in space on drag n drop in unity

There is a game Object "Heat" in Unity 2D. I am trying to drag and drop game object on another game object Sun using UI(works for unity version greater than 4.6). Drag works right but when I drop the object in space other than Sun, heat object does not retain its original position. I tried to make it work using colliders and raycasting but it does not seem to work. Here is the code:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class Drag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
public static GameObject itemBeingDragged;
public static Vector2 startPos;
void Start () {
}
#region IBeginDragHandler implementation
public void OnBeginDrag (PointerEventData eventData)
{
itemBeingDragged = gameObject;
startPos = transform.position;
}
#endregion
#region IDragHandler implementation
public void OnDrag (PointerEventData eventData)
{
transform.position = eventData.position;
}
#endregion
#region IEndDragHandler implementation
public void OnEndDrag (PointerEventData eventData)
{
//if itemBeingDragged is in Space then move it to its original position and then assign null
//itemBeingDragged = null;
RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector2.zero);
if (hit.collider != null)
{
print ("Inside hit.collider" + hit.collider.name);
//Itembeing Dragged ... set it to startPos if released in space
if (hit.collider.gameObject.name == "Heat")
{
LeanTween.move (hit.collider.gameObject,PublicVariables.startPosHeat, 1.5f);
}
}
}
#endregion
}
Any help is much appreciated. Thanks.

Categories