I have imported ienddraghandler, and my other drag methods work just fine. However, my onEndDrag is activated only every other (end of drag).
Example: Grab Object, drag object from point a to point b, let go, and onEndDrag is not called. Go through same exact process again and it is called.
It doesn't just happen the first time the app is booted up, it will continue to happen exactly in that order.
My guess is that it has something to do with a bool which would explain the "every other time" (possibly the dragging bool associated with drag handlers?)
Couldn't find others with the same problem. Thanks and have a great day.
public class VideoMovement : MonoBehaviour, IPointerClickHandler, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public VideoModule videoModule;
Camera mainCamera;
private bool dragging1 = false;
protected void OnEnable()
{
mainCamera = Camera.main;
m_MapMovementListener = GameObject.Find("EditorManagers").GetComponent<MapMovementListener>();
reSizeArrow = videoModule.transform.GetChild(1).gameObject;
}
protected void Update()
{
Debug.Log(dragging);
if (SiteCameraEditor.instance.shouldShowUI)
{
SizeManager();
}
}
public void OnBeginDrag(PointerEventData eventData)
{
if (SiteCameraEditor.instance.shouldShowUI)
{
VisualRepresentationManager(false);
m_Video_Transform = transform.parent;
m_VideoInitialPosition_Vector3 = m_Video_Transform.position;
m_Initial_Position = eventData.pointerCurrentRaycast.worldPosition;
videoModule.ElementData.Imager.homePresetPoint = m_Video_Transform.position;
m_Imager = FindImagerWithID(m_Video_Transform.GetComponent<VideoModule>().ElementData.Imager.Id);
SiteCameraEditor.instance.DrawLine(m_Imager.transform.position, m_Video_Transform.position, Color.red);
SiteCameraEditor.instance.SelectCamera(m_Video_Transform.GetComponent<VideoModule>().ElementData.Imager.gameObject);
//SiteCameraEditor.instance.UpdateUI();
m_MapMovementListener.SetObjectToMove(this);
}
}
public void OnEndDrag(PointerEventData eventData)
{
if(SiteCameraEditor.instance.shouldShowUI)
{
VisualRepresentationManager(true);
Debug.Log("OnEndDrag worked");
SiteCameraEditor.instance.UpdateUI();
}
}
SiteCameraEditor.instance.shouldShowUI is always true
deleted most of the code, this is what should be relevant
However there is an update loop that contains
protected void Update()
{
//Debug.Log(dragging);
if (SiteCameraEditor.instance.shouldShowUI)
{
SizeManager();
}
if(SiteCameraEditor.instance.shouldShowUI && reSizeArrow.activeInHierarchy)
{
reSizeArrow.SetActive(false);
}
try
{
if (!dragging1)
{
return;
}
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 wolrdSpaceNormal = transform.TransformDirection(Vector3.back);
Plane moveAxis = new(wolrdSpaceNormal, transform.position);
if (moveAxis.Raycast(ray, out float intersect))
{
Vector3 movePosition = ray.GetPoint(intersect);
Vector3 localClickPosition = transform.parent.transform.InverseTransformPoint(clickPosition);
Vector3 localMovePosition = transform.parent.transform.InverseTransformPoint(movePosition);
float offsetX = offsetRatioX * (localMovePosition.x - localClickPosition.x);
float offsetY = offsetRatioY * (localMovePosition.y - localClickPosition.y);
Mesh mesh = GetComponentInChildren<MeshFilter>().mesh;
Vector2[] uvs = mesh.uv;
float uvsSizeX = originalUVs[1].x - originalUVs[0].x;
float uvsSizeY = originalUVs[1].y - originalUVs[0].y;
float startX = originalUVs[0].x - offsetX;
float endX = originalUVs[1].x - offsetX;
float startY = originalUVs[0].y - offsetY;
float endY = originalUVs[1].y - offsetY;
// X TOO LEFT
if (startX <= 0)
{
startX = 0;
endX = startX + uvsSizeX;
}
// X TOO RIGHT
else if (endX >= 1)
{
endX = 1;
startX = endX - uvsSizeX;
}
// Y TOO DOWN
if (startY <= 0)
{
startY = 0;
endY = startY + uvsSizeY;
}
// X TOO UP
else if (endY >= 1)
{
endY = 1;
startY = endY - uvsSizeY;
}
uvs[0] = new Vector2(startX, startY);
uvs[1] = new Vector2(endX, endY);
uvs[2] = new Vector2(endX, startY);
uvs[3] = new Vector2(startX, endY);
mesh.uv = uvs;
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
however even when commented out, the onEndDrag isn't fixed
Related
What Whip should look like
I'm trying to create a whip that can extend in any direction the mouse is facing after pressing a certain button. If there are "grabbable" objects in the way such as an enemy or box, it should latch onto those objects and pull them around to collide with other objects for a certain amount of time.
I know that I need the different sprite shots of the whip extending and latching for animation, but I have no idea how to implement this in code and how to get the whip to stop short if it detects a "grabbable" object.
Attach this script to your player, this should get the job done:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public Transform player = null;
public float speed = 30f;
public string grabbableTag = "grabbable";
private LineRenderer line = null;
private float timer = 0f;
private bool grabbing = false;
private bool reached = false;
private Vector2 from = Vector2.zero;
private Vector2 to = Vector2.zero;
private Vector2 target = Vector2.zero;
private Transform grabbable = null;
private void Start()
{
player = transform;
line = new GameObject("Line").AddComponent<LineRenderer>();
line.startColor = Color.red;
line.endColor = Color.red;
// Assign a material
line.gameObject.SetActive(false);
reached = false;
grabbing = false;
}
private void Update()
{
if(grabbing)
{
Grabbing();
}
else
{
if (Input.GetMouseButtonDown(0))
{
Grab();
}
}
}
private void Grab()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = Vector3.Distance(player.position, Camera.main.transform.position);
to = Camera.main.ScreenToWorldPoint(mousePosition);
from = player.position;
Vector2 direction = (to - from).normalized;
float distance = Vector2.Distance(from, to);
RaycastHit2D[] hits = Physics2D.RaycastAll(from, direction, distance);
grabbable = null;
for (int i = 0; i < hits.Length; i++)
{
if (hits[i].transform.tag == grabbableTag)
{
grabbable = hits[i].transform;
break;
}
}
if (grabbable != null)
{
distance = Vector2.Distance(player.position, grabbable.position);
to = from + direction * distance;
}
grabbing = true;
reached = false;
target = from;
timer = 0;
line.gameObject.SetActive(true);
line.positionCount = 2;
line.SetPosition(0, from);
line.SetPosition(1, from);
}
private void Grabbing()
{
if (reached)
{
target = Vector2.Lerp(target, from, speed * Time.deltaTime);
if (target == from)
{
GrabDone(grabbable);
grabbing = false;
line.gameObject.SetActive(false);
}
}
else
{
target = Vector2.Lerp(target, to, speed * Time.deltaTime);
if(target == to)
{
reached = true;
}
}
line.SetPosition(1, target);
if (reached && grabbable != null)
{
grabbable.position = target;
}
}
private void GrabDone(Transform grabbed)
{
if(grabbed != null)
{
// Do somthing ...
Destroy(grabbed.gameObject);
}
}
}
I'm making a mobile game that uses trajectory to find out the next path from my player. When the player is silent the trajectory works very well, but when the player is moving the trajectory sometimes moves on its own even though it returns to its proper position later, but this is very disturbing.
Here's the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class PlayerMovement : MonoBehaviour
{
public static PlayerMovement Instance;
Rigidbody2D rb;
Vector3 startPos;
Vector3 endPos;
[HideInInspector] public Vector3 initPos;
[HideInInspector] public Vector3 direction;
public static Vector3 anotherSpeed; // Only for trajectory
float speedMultiplier = 1.5f;
public GameObject trajectoryDot;
GameObject[] trajectoryDots;
public int numbersOfTrajectory;
float trajectoryDotsDistance = 0.001f;
public static float energy = 100f;
public Slider energyBar;
float slowDownFactor = 0.3f;
private void Start()
{
if (!Instance)
Instance = this;
rb = GetComponent<Rigidbody2D>();
trajectoryDots = new GameObject[numbersOfTrajectory];
}
void Update()
{
anotherSpeed = direction;
if (!Pause.isPaused)
{
// Get Start Position
if (Input.GetMouseButtonDown(0))
{
// Instansiate The Trajectory
for (int i = 0; i < numbersOfTrajectory; i++)
{
trajectoryDots[i] = Instantiate(trajectoryDot,gameObject.transform.position, gameObject.transform.rotation);
}
}
// Get Position When Dragging
if (Input.GetMouseButton(0))
{
EnableSlowMotion();
// Get Drag Position
endPos = Camera.main.ScreenToWorldPoint(Input.mousePosition) + new Vector3(0, 0, 10);
startPos = gameObject.transform.position;
// Get The Speed
direction = endPos - startPos;
direction = direction.normalized;
direction = Vector3.Lerp(transform.position, direction, 500 * Time.deltaTime);
direction = direction * 18;
// Update The Trajectory Position
for (int i = 0; i < numbersOfTrajectory; i++)
{
trajectoryDots[i].transform.position = calculatePosition(i * trajectoryDotsDistance);
}
}
// Get Position When Realeasing
if (Input.GetMouseButtonUp(0))
{
DisableSlowMotion();
// enable Gravity
rb.gravityScale = 1f;
// Move The Player
rb.velocity = new Vector2(direction.x * speedMultiplier, direction.y * speedMultiplier);
// Destroy The Trajectory When Player Release
for (int i = 0; i < numbersOfTrajectory; i++)
{
Destroy(trajectoryDots[i]);
}
}
}
CameraZoom();
ControlsChecker();
}
// Calculate The Trajectory Prediction
Vector2 calculatePosition(float elapsedTime)
{
return new Vector2(startPos.x, startPos.y) +
new Vector2(anotherSpeed.x * speedMultiplier, anotherSpeed.y * speedMultiplier) * elapsedTime +
0.5f * Physics2D.gravity * elapsedTime * elapsedTime;
}
// Check Controls Is pull or push
void ControlsChecker()
{
if (PlayerPrefs.GetInt("Controls") == 1)
{
direction = direction;
anotherSpeed = anotherSpeed;
}
else
{
direction = -direction;
anotherSpeed = -anotherSpeed;
}
}
void EnableSlowMotion()
{
Time.timeScale = slowDownFactor;
Time.fixedDeltaTime = 0.02f * Time.timeScale;
}
void DisableSlowMotion()
{
Time.timeScale = 1f;
Time.fixedDeltaTime = 0.02F;
}
}
void CameraZoom()
{
if (Input.GetMouseButton(0))
{
vcam.m_Lens.OrthographicSize += 0.1f;
if (vcam.m_Lens.OrthographicSize >= maxZoom)
{
vcam.m_Lens.OrthographicSize = maxZoom;
}
}
else if (Input.GetMouseButtonUp(0))
{
zoomIn = true;
}
if (zoomIn)
{
vcam.m_Lens.OrthographicSize -= 0.2f;
if (vcam.m_Lens.OrthographicSize <= minZoom)
{
vcam.m_Lens.OrthographicSize = minZoom;
zoomIn = false;
}
}
}
so I get the player's movement direction from the calculation based on the point where I touch and the point when I release touch (dragging). Did I make a mistake in the code that caused my trajectory to vibrate often? I really need help here, thanks in advance.
I need some help to swipe object or we can say move object on which i have touched.
I have created code in which i'm able to drag only one button.
Suppose i touched on first button it should be active for swipe.
Here is my screen show.
I want to create code for every button for dragging that button on Swipe.
Here is my buttons
using UnityEngine;
public class SwipeJump : MonoBehaviour
{
private Vector2 startTouchPosition, endTouchPosition;
private Rigidbody2D rb;
private float jumpForce = 700f;
private bool jumpAllowed = false;
float deltaX, deltaY;
// Use this for initialization
private void Start ()
{
rb = GetComponent<Rigidbody2D> ();
#region newcode
PhysicsMaterial2D mat = new PhysicsMaterial2D();
//mat.bounciness = 0.75f;
//mat.friction = 0.4f;
GetComponent<CircleCollider2D>().sharedMaterial = mat;
#endregion
}
// Update is called once per frame
private void Update ()
{
//SwipeCheck ();
#region newcode
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
switch (touch.phase)
{
case TouchPhase.Began:
if (GetComponent<Collider2D>() == Physics2D.OverlapPoint(touchPos))
{
deltaX = touchPos.x - transform.position.x;
deltaY = touchPos.y - transform.position.y;
jumpAllowed = true;
rb.freezeRotation = true;
rb.velocity = new Vector2(0, 0);
rb.gravityScale = 0;
GetComponent<Collider2D>().sharedMaterial = null;
}
break;
case TouchPhase.Moved:
if (GetComponent<Collider2D>() == Physics2D.OverlapPoint(touchPos) && jumpAllowed)
{
rb.MovePosition(new Vector2(touchPos.x - deltaX, touchPos.y - deltaY));
}
break;
case TouchPhase.Ended:
jumpAllowed = false;
rb.freezeRotation = false;
rb.gravityScale = 2;
PhysicsMaterial2D mat = new PhysicsMaterial2D();
//mat.bounciness = 0.75f;
//mat.friction = 0.4f;
GetComponent<CircleCollider2D>().sharedMaterial = mat;
break;
}
}
#endregion
}
}
I've written the following code making the gun move to the guy's shoulder position when he stops shooting and it does work...BUT ONLY ONCE. After that, it starts not to meet the target even though it's coordinates remain the same. I've tried it with Lerp, SmoothDamp, MoveTowards...still don't get where the problem lies.
P.S. The gun moves to the shoulder when shooting perfectly, it starts happening when the character stops shooting and tries to go back to the Idle pose.
EDIT: Turns out there's also something wrong with rotation...or maybe it's just rotation. I don't even know at this point.
THE VIDEO of what's going on: https://youtu.be/CheQiomYtm8
THE CODE:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnitControl;
public class BlastIKController : MonoBehaviour
{
public WeaponState wpState;
public GameObject weapon;
public GameObject RightShoulder;
public GameObject HumanSpine;
public GameObject WeaponSpawn;
public LayerMask lmask;
public BlastIKHandler ikHandle;
public Material targetMat;
public Material defMat;
public GameObject target;
public GameObject WeaponIdle;
public bool isShooting = false;
//public bool InIdle = true;
LineRenderer ShootLine;
public GameObject WeaponInstance;
Animator anim;
public float speedMove;
public float speedRot;
// Use this for initialization
void Awake()
{
GameObject weaponInst = Instantiate(weapon, WeaponSpawn.transform);
WeaponInstance = weaponInst;
WeaponInstance.transform.localPosition = new Vector3(0, 0, 0);
wpState = weaponInst.GetComponent<WeaponState>();
ikHandle = this.GetComponent<BlastIKHandler>();
ShootLine = this.GetComponent<LineRenderer>();
anim = this.GetComponent<Animator>();
ikHandle.RightShoulder = RightShoulder;
ikHandle.leftHandTarget = wpState.leftHandIdle.transform;
ikHandle.rightHandTarget = wpState.rightHandTarget.transform;
//Позиция оружия
wpState.shoulder.transform.position = ikHandle.WeaponIdlePos.position;
wpState.shoulder.transform.rotation = ikHandle.WeaponIdlePos.rotation;
}
// Update is called once per frame
void Update()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
#region SearchTarget
if (Physics.Raycast(ray, out hit, Mathf.Infinity, lmask))
{
if (hit.collider.gameObject.tag == "Target")
{
ShootLine.positionCount = 2;
ShootLine.SetPosition(0, HumanSpine.transform.position);
ShootLine.SetPosition(1, hit.collider.gameObject.transform.position);
if (Input.GetMouseButton(0))
{
if (target == null)
{
target = hit.collider.gameObject;
MeshRenderer ms = hit.collider.gameObject.GetComponent<MeshRenderer>();
ms.material = targetMat;
ikHandle.targetPos = hit.collider.gameObject;
}
else
{
MeshRenderer ms = target.GetComponent<MeshRenderer>();
ms.material = defMat;
target = hit.collider.gameObject;
ms = target.GetComponent<MeshRenderer>();
ms.material = targetMat;
ikHandle.targetPos = hit.collider.gameObject;
}
}
}
}
#endregion
#region Shooting
Shooting();
if (isShooting)
{
if (target != null)
{
bool isShoot = anim.GetBool("Shoot");
if (!isShoot)
{
StartCoroutine(MoveToShoot(RightShoulder.transform.position));
ikHandle.leftHandTarget = wpState.leftHandTarget.transform;
anim.SetBool("Shoot", true);
//InIdle = false;
}
}
}
else
{
// float stepMove = speedMove * Time.deltaTime;
// wpState.shoulder.transform.position = Vector3.Lerp(wpState.shoulder.transform.position, ikHandle.WeaponIdlePos.position, stepMove);
// //if (!InIdle)
// //{
// // StartCoroutine(MoveToIdle(ikHandle.WeaponIdlePos.position));
//// }
// //InIdle = true;
// //float stepMove = speedMove * Time.deltaTime;
// //while (wpState.shoulder.transform.position != ikHandle.WeaponIdlePos.position)
// //{
// // wpState.shoulder.transform.position = Vector3.Lerp(wpState.shoulder.transform.position, ikHandle.WeaponIdlePos.position, stepMove);
// //}
// ////wpState.shoulder.transform.position = ikHandle.WeaponIdlePos.position;
// ////wpState.shoulder.transform.position = Vector3.MoveTowards(wpState.shoulder.transform.position, ikHandle.WeaponIdlePos.position, stepMove);
// float stepRot = speedRot * Time.deltaTime;
// //while (wpState.shoulder.transform.rotation != ikHandle.WeaponIdlePos.rotation)
// //{
// wpState.shoulder.transform.rotation = Quaternion.Slerp(wpState.shoulder.transform.rotation, ikHandle.WeaponIdlePos.rotation, stepRot);
// //}
// ////wpState.shoulder.transform.rotation = ikHandle.WeaponIdlePos.rotation;
// ikHandle.leftHandTarget = wpState.leftHandIdle.transform;
// anim.SetBool("Shoot", false);
}
#endregion
}
void LateUpdate()
{
if (!isShooting)
{
float stepMove = speedMove * Time.deltaTime;
stepMove += Time.deltaTime / speedMove;
Vector3 velocity = Vector3.zero;
//.shoulder.transform.position = Vector3.Lerp(wpState.shoulder.transform.position, ikHandle.WeaponIdlePos.position, stepMove);
wpState.shoulder.transform.position = Vector3.MoveTowards(wpState.shoulder.transform.position, ikHandle.WeaponIdlePos.position, stepMove);
//wpState.shoulder.transform.position = Vector3.SmoothDamp(wpState.shoulder.transform.position, ikHandle.WeaponIdlePos.position, ref velocity, stepMove);
// wpState.shoulder.transform.position = Vector3.SmoothDamp()
float stepRot = speedRot * Time.deltaTime;
wpState.shoulder.transform.rotation = Quaternion.Slerp(wpState.shoulder.transform.rotation, ikHandle.WeaponIdlePos.rotation, stepRot);
ikHandle.leftHandTarget = wpState.leftHandIdle.transform;
anim.SetBool("Shoot", false);
}
}
void Shooting()
{
if (Input.GetKeyDown(KeyCode.S))
{
isShooting = !isShooting;
}
}
IEnumerator MoveToShoot(Vector3 WPposition)
{
float step = speedMove * Time.deltaTime;
while (wpState.shoulder.transform.position != WPposition)
{
wpState.shoulder.transform.position = Vector3.Lerp(wpState.shoulder.transform.position, WPposition, step);
Vector3 relativeWeaponPos = ikHandle.targetPos.transform.position - wpState.shoulder.transform.position;
Quaternion WeaponRotation = Quaternion.LookRotation(relativeWeaponPos);
wpState.shoulder.transform.rotation = Quaternion.Slerp(wpState.shoulder.transform.rotation, WeaponRotation, step);
yield return null;
}
}
IEnumerator MoveToIdle(Vector3 WPposition)
{
float stepMove = speedMove * Time.deltaTime;
float stepRot = speedRot * Time.deltaTime;
while (wpState.shoulder.transform.position != WPposition)
{
wpState.shoulder.transform.position = Vector3.Lerp(wpState.shoulder.transform.position, WPposition, stepMove);
wpState.shoulder.transform.rotation = Quaternion.Slerp(wpState.shoulder.transform.rotation, ikHandle.WeaponIdlePos.transform.rotation, stepRot);
yield return null;
}
wpState.shoulder.transform.position = Vector3.Lerp(wpState.shoulder.transform.position, ikHandle.WeaponIdlePos.position, stepMove);
}
}
So, it was the following. It turns out that the coroutines got mixed up in Update and they worked at the same time.
So...I removed all coroutines from the code and then moved and rotated using Lerp and sLerp in the update.
There's one thing though, I also had to add a check for both bositions to meet, and after that it starts shooting and only then.
P.S. I can add the code I changed later if you like.
I was following a tutorial online, and basically the script is telling the gameObject to instantiate a clone of itself if the camera gets to a certain position. The last lines that I am confused about are these
if (rightOrLeft > 0)
{
newBuddy.GetComponent<Tiling>().hasALeftBuddy = true;
}
else
{
newBuddy.GetComponent<Tiling>().hasARightBuddy = true;
}
}
In short, I'm not really up to par with the syntax or math right here. Could someone please help in clearing it up for me?
using UnityEngine;
using System.Collections;
[RequireComponent (typeof(SpriteRenderer))]
public class Tiling : MonoBehaviour {
public int offsetX = 2;
public bool hasARightBuddy = false;
public bool hasALeftBuddy = false;
public bool reverseScale = false;
private float spriteWidth = 0f;
private Camera cam;
private Transform myTransform;
void Awake () {
cam = Camera.main;
myTransform = transform;
}
// Use this for initialization
void Start () {
SpriteRenderer sRenderer = GetComponent<SpriteRenderer>();
spriteWidth = sRenderer.sprite.bounds.size.x;
}
// Update is called once per frame
void Update ()
{
if (hasALeftBuddy == false || hasARightBuddy == false)
{
float camHorizontalExtend = cam.orthographicSize * Screen.width/Screen.height;
float edgeVisiblePositionRight = (myTransform.position.x + spriteWidth/2) - camHorizontalExtend; //sprite width/2..51.2
//(0 + 51.2 - 26.67315 = 24.52685)
//(102.4 + 51.2 - 26.67315 = 126.92685) etc.. //clone of the myTransform
float edgeVisiblePositionLeft = (myTransform.position.x - spriteWidth/2) + camHorizontalExtend; // (0 - 51.2 + 26.67315 = -24.52685)
// (-102.4 - 51.2 + 26.67315 = -126.92685) etc..//clone of the myTransform
if (cam.transform.position.x >= edgeVisiblePositionRight - offsetX && hasARightBuddy == false)
{
MakeNewBuddy (1);
hasARightBuddy = true;
}
else if (cam.transform.position.x <= edgeVisiblePositionLeft + offsetX && hasALeftBuddy == false)
{
MakeNewBuddy (-1);
hasALeftBuddy = true;
}
}
}
void MakeNewBuddy (int rightOrLeft)
{
Vector3 newPosition = new Vector3 (myTransform.position.x + spriteWidth * rightOrLeft, myTransform.position.y, myTransform.position.z);
Transform newBuddy = Instantiate (myTransform, newPosition, myTransform.rotation) as Transform;
if (reverseScale == true)
{
newBuddy.localScale = new Vector3 (newBuddy.localScale.x*-1, newBuddy.localScale.y, newBuddy.localScale.z);
}
if (rightOrLeft > 0)
{
newBuddy.GetComponent<Tiling>().hasALeftBuddy = true;
}
else
{
newBuddy.GetComponent<Tiling>().hasARightBuddy = true;
}
}
}
}
looks to me like the code is telling the current game object that it has a neighbour when the new neighbour is created.
The boolean has a neighbour variables are handy for figuring out that this creation process doesn't need to happen again :)