Detecting touch on a specific object in Unity - unity3d

working on an android game in Unity 2D. Long story short, I have two separate objects in the scene which have this script attached on:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwipeScript : MonoBehaviour
{
Vector2 startPos, endPos, direction;
float touchTimeStart, touchTimeFinish, timeInterval;
public static int brojbacanja=0;
public static bool bacenaprva = false;
[Range (0.05f, 1f)]
public float throwForce = 0.3f;
void Update(){
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began && brojbacanja == 0) {
touchTimeStart = Time.time;
startPos = Input.GetTouch (0).position;
}
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Ended && brojbacanja == 0) {
touchTimeFinish = Time.time;
timeInterval = touchTimeFinish - touchTimeStart;
endPos = Input.GetTouch (0).position;
direction = startPos - endPos;
GetComponent<Rigidbody2D> ().AddForce (-direction / timeInterval * throwForce);
brojbacanja = 1;
bacenaprva = true;
}
}
}
What this does is pretty much alowing me to swipe anywhere on the screen and throw an object which it's attached to. Since I have two different objects which I would like to throw separately, I want to change it a bit so when I touch object which I want to throw, other one stays still. I read about this problem alredy and tried using Raycast and OnMouseDown() but didn't know how to implement it.
If anyone can help, would be grateful.

Since this script will be on each object in the scene you will need to have an extra variable and a check to see if the initial touch is intersecting your object.
If you are using 3D objects (which I am assuming because you mentioned ray tracing), then you will want something that converts the touch position on the screen to a ray, that you then cast to see if it intersects your object. Your object will have to have collision for this to work.
public class SwipeScript : MonoBehaviour
{
// added these two values, set the coll value to your collider on this object.
bool isTouching;
public Collider coll;
Vector2 startPos, endPos, direction;
float touchTimeStart, touchTimeFinish, timeInterval;
public static int brojbacanja=0;
public static bool bacenaprva = false;
[Range (0.05f, 1f)]
public float throwForce = 0.3f;
void Update(){
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began && brojbacanja == 0) {
if(IsTouchOverThisObject(Input.GetTouch(0))) {
isTouching = true;
touchTimeStart = Time.time;
startPos = Input.GetTouch (0).position;
}
}
if (isTouching && Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Ended && brojbacanja == 0) {
isTouching = false;
touchTimeFinish = Time.time;
timeInterval = touchTimeFinish - touchTimeStart;
endPos = Input.GetTouch (0).position;
direction = startPos - endPos;
GetComponent<Rigidbody2D> ().AddForce (-direction / timeInterval * throwForce);
brojbacanja = 1;
bacenaprva = true;
}
}
bool IsTouchOverThisObject(Touch touch) {
Ray ray = Camera.main.ScreenPointToRay(new Vector3(touch.position.x, touch.position.y, 0));
RaycastHit hit;
// you may need to adjust the max distance paramter here based on your
// scene size/scale.
return coll.Raycast(ray, out hit, 1000.0f);
}
}

Related

How to spawn multiple prefab, with individual physics

I Did apply some of the responses , most likely in the wrong way.. this is still not working with this RAYCAST. What am I doing wrong here?
Want to spawn a prefab, which is a a ball, this ball is flying forward on flick finger on the screen.
What I want is to spawn OnClick FEW/Multiple of this prefab.
, prefab is spawning on Raycast Hit, BUT.. when I am flicking the object EVERY prefab in the scene is moving in the same way.
If I flick first one in to the Left, it goes there, but If now I flick second one to right, BOTH go to the RIGHT, but I would like them to work independent. Maybe this is easy fix to this but I can't find answer. (I'm planning to have up to 30/50 of this prefabs, so attaching separate scripts would be bit time consuming)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallScript1 : MonoBehaviour
{
Vector2 startPos, endPos, direction;
float touchTimeStart, touchTimeFinish;
public float timeInterval = 5f;
public float throwForceInXandY = 1f;
public float throwForceinZ = 40f;
public static bool SpawnButtonAppear = true;
public static bool thrown = false;
public static bool moving = false;
public static bool fly = false;
public bool Pressed = false;
Rigidbody rb;
public GameObject player;
public Vector3 originalPos;
public GameObject playerPrefab;
string touched;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
}
private void OnMouseDown()
{
PlayerTest.clicked = true;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit _hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out _hit))
{
touched = _hit.collider.tag;
if (touched == "Player")
{
Invoke("spawned", 0.5f);
}
}
}
if (touched == "Player")
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
touchTimeStart = Time.time;
startPos = Input.GetTouch(0).position;
}
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
fly = false;
touchTimeFinish = Time.time;
endPos = Input.GetTouch(0).position;
direction = startPos - endPos;
rb.isKinematic = false;
rb.AddForce(-direction.x * throwForceInXandY, -direction.y * throwForceInXandY, throwForceinZ * timeInterval);
BackWall.canSpawnNow = 1;
}
}
}
public void spawned()
{
GameObject spawnedprefab = Instantiate(playerPrefab, new Vector3(originalPos.y, originalPos.x, originalPos.z), Quaternion.identity);
Destroy(spawnedprefab, 5f);
}
The thrown variable is not declared inside your class, so when you set it to true you are setting it true for all the instances of the class.
Declare the bool thrown; inside the EnemySpawn class, so that OnMouseDown, only the corresponding intance's thrown variable is set to true.

restrict camera movement, Camera moves out of bounds

I'm creating a simple camera pan and scroll for my mobile game and need some help.
Right now with the code I have a player can scroll of the map I created.
I got the code from this youtube video (for context) https://gist.github.com/ditzel/836bb36d7f70e2aec2dd87ebe1ede432
https://www.youtube.com/watch?v=KkYco_7-ULA&ab_channel=DitzelGames
Do you know how I could fix this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScrollAndPinch : MonoBehaviour
{
#if UNITY_IOS || UNITY_ANDROID
public Camera Camera;
public bool Rotate;
protected Plane Plane;
public Transform Map;
float distance;
private void Awake()
{
if (Camera == null)
Camera = Camera.main;
Input.multiTouchEnabled = true;
}
private void Update()
{
//Update Plane
if (Input.touchCount >= 1)
Plane.SetNormalAndPosition(transform.up, transform.position);
var Delta1 = Vector3.zero;
var Delta2 = Vector3.zero;
//Scroll
if (Input.touchCount >= 1)
{
Delta1 = PlanePositionDelta(Input.GetTouch(0));
if (Input.GetTouch(0).phase == TouchPhase.Moved)
Camera.transform.Translate(Delta1, Space.World);
}
}
protected Vector3 PlanePositionDelta(Touch touch)
{
//not moved
if (touch.phase != TouchPhase.Moved)
return Vector3.zero;
//delta
var rayBefore = Camera.ScreenPointToRay(touch.position - touch.deltaPosition);
var rayNow = Camera.ScreenPointToRay(touch.position);
if (Plane.Raycast(rayBefore, out var enterBefore) && Plane.Raycast(rayNow, out var enterNow))
return rayBefore.GetPoint(enterBefore) - rayNow.GetPoint(enterNow);
//not on plane
return Vector3.zero;
}
protected Vector3 PlanePosition(Vector2 screenPos)
{
//position
var rayNow = Camera.ScreenPointToRay(screenPos);
if (Plane.Raycast(rayNow, out var enterNow))
return rayNow.GetPoint(enterNow);
return Vector3.zero;
}
#endif
}
You can put in the update a control with the bounds of your area with a bool like this :
if(Camera.transform.position.x > valuexmax || Camera.transform.position.x < valuexmin
|| Camera.transform.position.y > valueymax || Camera.transform.position.y < valueymin)
{
InBounds = false; //just a bool variable set to true in start
}
And then you can put in the scroll something like this
if (Input.touchCount >= 1 && InBounds == true)
{
Delta1 = PlanePositionDelta(Input.GetTouch(0));
if (Input.GetTouch(0).phase == TouchPhase.Moved)
Camera.transform.Translate(Delta1, Space.World);
}
if(InBounds == false)
{
// reset position
}

How to convert keyboard controls to touch screen in Unity

Complete newbie here. Using Unity C#. I'm looking at moving my PONG game from keyboard control to touch screen. Here is my working keyboard code:
// Player 1 => Controls left bat with W/S keys
public GameObject leftBat;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//Defualt speed of the bat to zero on every frame
leftBat.GetComponent<Rigidbody>().velocity = new Vector3(0f, 0f, 0f);
//If the player is pressing the W key...
if (Input.GetKey (KeyCode.W)) {
//Set the velocity to go up 1
leftBat.GetComponent<Rigidbody>().velocity = new Vector3(0f, 8f, 0f);
}
//If the player is pressing the S key...
else if (Input.GetKey (KeyCode.S)) {
//Set the velocity to go down 1 (up -1)
leftBat.GetComponent<Rigidbody>().velocity = new Vector3(0f, -8f, 0f);
}
}
I found this code and been playing around with it but to now avail.
using UnityEngine;
using System.Collections;
public class Player_Input_Controller : MonoBehaviour {
public GameObject leftBat;
public float paddleSpeed = 1f;
public float yU;
public float yD;
private Ray ray;
private RaycastHit rayCastHit;
private Vector3 playerPos = new Vector3(0, -9.5f, 0);
// Update is called once per frame
void Update () {
if (Input.GetMouseButton (0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out rayCastHit)){
Vector3 position = rayCastHit.point;
float yPos = position.y;
playerPos = new Vector3(Mathf.Clamp(yPos, yU, yD), -9.5f, 0f);
transform.position = playerPos;
}
}
}
}
Any one have a touchscreen Pong script I could use, or know how to edit this one?
Again, I'm really new and I'm sorry if I look like the Dummy in the class.
Thanks for any help provided. I REALLY appreciate it. This is the last hurdle in completing my game.
In my opinion, you do not need any raycasting. Because you are working in 2D and you are only concerned about the y value of Input.mousePosition. Therefore, you can calculate the extent of your screen using your camera's z value. If your camera is at (0, 0, -10) lets say your extents in the game will be -5 - BatOffset to 5+BatOffset in your world coordinates. Therefore, you somehow need a function to map Screen.height to your world coordinate extents as you can see from the image.
In conclusion you need to find Input.mousePosition.y divide it to Screen.height. This will give you the ratio where you touch or click. Then find the position in world space.
Note that: you can also use Input.touchPosition.y. Following script will work for you to do this operation:
public GameObject cam;
private Vector3 batPos;
private float minY;
private float maxY;
private int Res;
private float deltaY;
void Start () {
minY = cam.transform.position.z / 2 - gameObject.transform.localScale.y;
maxY = (-cam.transform.position.z / 2) + gameObject.transform.localScale.y;
deltaY = maxY - minY;
Debug.Log(minY + " " + maxY + " " + deltaY);
Res = Screen.height;
batPos = gameObject.transform.position;
}
void Update () {
if(Input.GetMouseButtonDown(0))
{
// we find the height we have to go up from minY
batPos.y =minY + Input.mousePosition.y / Res * deltaY;
gameObject.transform.position = batPos;
}
}
This works for me in the editor when you click on screen with mouse. You just have to change the parts Input.GetMouseButtonDown to Touch commands such as Touch.tapCount > 0. Also this script should be attached to the bat. Good luck!
Also You can use Orthographic camera and Orthographic camera size instead of cam.transformation.z
May be helpfull
create script. for example player.cs
public class PlayerController : MonoBehaviour
{
bool swipeRight = false;
bool swipeLeft = false;
bool touchBlock = true;
bool canTouchRight = true;
bool canTouchLeft = true;
void Update()
{
swipeLeft = Input.GetKeyDown("a") || Input.GetKeyDown(KeyCode.LeftArrow);
swipeRight = Input.GetKeyDown("d") || Input.GetKeyDown(KeyCode.RightArrow);
TouchControl();
if(swipeRight) //rightMove logic
else if(swipeLeft) //leftMove logic
}
void TouchControl()
{
if(Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began )
{
//Jump logic
}
else if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved && touchBlock == true)
{
touchBlock = false;
// Get movement of the finger since last frame
var touchDeltaPosition = Input.GetTouch(0).deltaPosition;
Debug.Log("touchDeltaPosition "+touchDeltaPosition);
if(touchDeltaPosition.x > 0 && canTouchRight == true)
{
//rightMove
swipeRight = true; canTouchRight = false;
Invoke("DisableSwipeRight",0.2f);
}
else if(touchDeltaPosition.x < 0 && canTouchLeft == true)
{
//leftMove
swipeLeft = true; canTouchLeft = false;
Invoke("DisableSwipeLeft",0.2f);
}
}
}
void DisableSwipeLeft()
{
swipeLeft = false;
touchBlock = true;
canTouchLeft = true;
}
void DisableSwipeRight()
{
swipeRight = false;
touchBlock = true;
canTouchRight = true;
}
}

unity | Create and destroy Jostick dynamically with touch

I want to make a jostick that created (Instatiated or whatever) in touch position(Input.getTouch(i).position) and destroyed when user doesn't touch the screen anymore. This is the source code below. Please give me an idea how to do it. Thank you.
using UnityEngine;
using System.Collections;
public class joy : MonoBehaviour
{
public GameObject joystick; //Self explanitory
public GameObject bg; //Background object for the joystick boundaries
public const float deadzone = 0f; //Deadzone for the joystick
public const float radius = 2.0f; //The radius that the joystick thumb is allowed to move from its origin
public Camera cam;
protected Collider joyCol;
protected int lastfingerid = -1; //Used for latching onto the finger
public Vector2 position = Vector2.zero;
void Awake ()
{
joyCol = bg.GetComponent<Collider>();
}
public void Disable ()
{
gameObject.active = false; //Turns off the joystick when called
}
public void ResetJoystick () //Called when the joystick should be moved back to it's original position (relative to parent object)
{
lastfingerid = -1;
joystick.transform.localPosition = Vector3.zero;
}
void Update ()
{
if (Input.touchCount == 0)
{
ResetJoystick (); //I would have figured this would be obvious? :P
}
else
{
for (int i=0; i < Input.touchCount; i++)
{
Touch touch = Input.GetTouch(i);
bool latchFinger = false;
if (touch.phase == TouchPhase.Began) //When you begin the touch, the code here gets called once
{
//Vector3 touchpos = Input.GetTouch(i).position;
//touchpos.z = 0.0f;
//Vector3 createpos = cam.ScreenToWorldPoint(touchpos);
Ray ray = cam.ScreenPointToRay (touch.position); //Creates a ray at the touch spot
RaycastHit hit; //Used for determining if something was hit
//joystick = (GameObject)Instantiate(Resources.Load("Type3/joystick"),createpos, Quaternion.identity);
//bg = (GameObject)Instantiate(Resources.Load("Type3/Bg"),createpos, Quaternion.identity);
if (joyCol.Raycast(ray,out hit,Mathf.Infinity)) //The ray hit something...
{
if (hit.collider == joyCol) //Apparently, that ray hit your joystick
{
latchFinger = true; //This turns on and sets off a chain reaction
}
}
}
if (latchFinger ) //Latch finger being true turns this code on
{
if ((lastfingerid == -1 || lastfingerid != touch.fingerId))
{
lastfingerid = touch.fingerId;
}
}
if (lastfingerid == touch.fingerId) //The real meat of the code
{
Vector3 sTW = cam.ScreenToWorldPoint (new Vector3 (touch.position.x, touch.position.y, 1)); //Transforms the screen touch coordinates into world coordinates to move our joystick
joystick.transform.position = sTW; //Hurr :O
joystick.transform.localPosition = new Vector3(joystick.transform.localPosition.x,joystick.transform.localPosition.y,0);
//float xClamp = Mathf.Clamp (joystick.transform.localPosition.x, xClampMin, xClampMax); //Limit movement to the boundaries
//float yClamp = Mathf.Clamp (joystick.transform.localPosition.y, yClampMin, yClampMax);
/*float distFromCenter = Mathf.Sqrt(joystick.transform.localPosition.x*joystick.transform.localPosition.x + joystick.transform.localPosition.y*joystick.transform.transform.localPosition.y);
float actualPercent = Mathf.Clamp01(distFromCenter/radius);
float percent = Mathf.Clamp01((distFromCenter - deadzone)/(radius - deadzone));
*/
joystick.transform.localPosition = Vector3.ClampMagnitude(joystick.transform.localPosition,radius);
//joystick.transform.localPosition = new Vector3 (xClamp, yClamp, joystick.transform.localPosition.z); //Finally, the joystick moves like it should with everything in place
if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
{
ResetJoystick ();
}
}
Ray touchray = cam.ScreenPointToRay (touch.position); //Creates a ray at the touch spot
//RaycastHit hit; //Used for determining if something was hit
Debug.DrawRay (touchray.origin, touchray.direction * 100, Color.yellow); //Delete this line. It's not important.
}
}
//set our position variables x and y values to the joysticks values but clamped to a percent value instead of world coords
position.x = joystick.transform.localPosition.x/radius;
position.y = joystick.transform.localPosition.y/radius;
if(position.magnitude < deadzone)
{
position.x = 0;
position.y = 0;
}
}
}

Ball moves too far when it jumps. It can still be controlled while its in air. Unity3d player control script

I am working on unity ball game. My player is a ball and it uses a player control script. When the ball jumps in air, it can still be controlled and mo move to any direction while its in air. I do not want that as it fails the purpose of heaving a maze since it can fly above obstacles.
I am using a player control script that came with a free unity game kit. I have tried to fix it, but I am only capable of either removing the jump function or reducing its height, and could not fix the issue.
using UnityEngine;
using System.Collections;
public class PlayerControl : MonoBehaviour
{
private GameObject moveJoy;
private GameObject _GameManager;
public Vector3 movement;
public float moveSpeed = 6.0f;
public float jumpSpeed = 5.0f;
public float drag = 2;
private bool canJump = true;
void Start()
{
moveJoy = GameObject.Find("LeftJoystick");
_GameManager = GameObject.Find("_GameManager");
}
void Update ()
{
Vector3 forward = Camera.main.transform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
Vector3 forwardForce = new Vector3();
if (Application.platform == RuntimePlatform.Android)
{
float tmpSpeed = moveJoy.GetComponent<Joystick>().position.y;
forwardForce = forward * tmpSpeed * 1f * moveSpeed;
}
else
{
forwardForce = forward * Input.GetAxis("Vertical") * moveSpeed;
}
rigidbody.AddForce(forwardForce);
Vector3 right= Camera.main.transform.TransformDirection(Vector3.right);
right.y = 0;
right = right.normalized;
Vector3 rightForce = new Vector3();
if (Application.platform == RuntimePlatform.Android)
{
float tmpSpeed = moveJoy.GetComponent<Joystick>().position.x;
rightForce = right * tmpSpeed * 0.8f * moveSpeed;
}
else
{
rightForce= right * Input.GetAxis("Horizontal") * moveSpeed;
}
rigidbody.AddForce(rightForce);
if (canJump && Input.GetKeyDown(KeyCode.Space))
{
rigidbody.AddForce(Vector3.up * jumpSpeed * 100);
canJump = false;
_GameManager.GetComponent<GameManager>().BallJump();
}
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Destroy")
{
_GameManager.GetComponent<GameManager>().Death();
Destroy(gameObject);
}
else if (other.tag == "Coin")
{
Destroy(other.gameObject);
_GameManager.GetComponent<GameManager>().FoundCoin();
}
else if (other.tag == "SpeedBooster")
{
movement = new Vector3(0,0,0);
_GameManager.GetComponent<GameManager>().SpeedBooster();
}
else if (other.tag == "JumpBooster")
{
movement = new Vector3(0,0,0);
_GameManager.GetComponent<GameManager>().JumpBooster();
}
else if (other.tag == "Teleporter")
{
movement = new Vector3(0,0,0);
_GameManager.GetComponent<GameManager>().Teleporter();
}
}
void OnCollisionEnter(Collision collision)
{
if (!canJump)
{
canJump = true;
_GameManager.GetComponent<GameManager>().BallHitGround();
}
}
void OnGUI()
{
GUI.Label(new Rect(300,10,100,100),"X: " + moveJoy.GetComponent<Joystick>().position.x.ToString());
GUI.Label(new Rect(300,30,100,100),"Y: " + moveJoy.GetComponent<Joystick>().position.y.ToString());
}
}
The question has been answered. Now how to use this script -> Create a sphere and give it "Sphere Collider", "Mesh Renderer", "Rigidbody", "Player Control(Script)" Under player control script put this script and your done. Now you have a ball that can be controlled in ios,android and pc i guess and can jump.
I think canJump flag says "Player on the ground". So, if you "can't jump", that means you shouldn't allow gamer to control the character as it is flying. Check it in very start of Update() and call return; if canJump == false