Unity2D: How to check if a sprite is clicked/touched - c#

I am making a 2D platformer in Unity for iOS, and I need to make buttons so the user can move, but for some reason, the script I made is not working. Also, the script I am putting in is just for the Left button, but the Right and Jump scripts work the same way.
Code:
using UnityEngine;
using System.Collections;
public class Left : MonoBehaviour {
public GameObject player;
public GameObject button;
void Start () {
}
void Update () {
if (Input.GetKey (KeyCode.A)) {
player.GetComponent<PlayerAnimator>().animationState = MovementState.moveLeft;
player.transform.position+=Vector3.left / 30;
}
if (Input.touchCount > 0){
foreach(Touch touch in Input.touches){
Collider2D col = button.GetComponent<Collider2D>();
Vector3 tpos = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 0));
if(col.bounds.Contains(tpos)){
Debug.Log ("left");
player.GetComponent<PlayerAnimator>().animationState = MovementState.moveLeft;
player.transform.position+=Vector3.left / 30;
}
}
}
}
void OnMouseOver(){
Debug.Log ("left");
player.GetComponent<PlayerAnimator>().animationState = MovementState.moveLeft;
player.transform.position+=Vector3.left / 30;
}
void OnMouseUp(){
player.GetComponent<PlayerAnimator> ().animationState = MovementState.idleLeft;
}
}

Don't use OnMouseOver for android application. It isn't usable on touch devices. But instead of it, OnMouseDrag function will work.
void OnMouseDrag(){
Debug.Log ("left");
player.GetComponent<PlayerAnimator>().animationState = MovementState.moveLeft;
player.transform.position+=Vector3.left / 30;
}
Edit: Because OnMouseOver is called when position of mouse is over object but not clicked. Otherwise OnMouseDrag is called when position of mouse is over object and clicked. In mobile devices OnMouseOver situation isn't possible.

Related

Objects vanishing when clicked on / objects not moving towards mouse

Here's my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GoToMouse : MonoBehaviour
{
private Transform tf;
private bool Selected = false;
// Start is called before the first frame update
void Start()
{
tf = GetComponent<Transform>();
}
private void OnMouseDown()
{
if (Selected == false)
{
Selected = true;
}
if (Selected == true)
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
tf.position = mousePos;
}
}
private void OnMouseUp()
{
if (Selected == true)
{
Selected = false;
}
if (Selected == false)
{
}
}
// Update is called once per frame
void Update()
{
}
}
In this script, I want to do two things. I want an object to become selected when clicked and unselected when you let go of the mouse. When an object is selected I want it to move towards the mouse cursor. Basically, you can drag it around with the mouse cursor and throw it with physics.
This script has a couple problems.
Whenever I click the object it completely vanishes. I have no background or anything it could be going behind, so I don't know what is causing this. The object also doesn't move anywhere (I checked its transform) So it appears it's sprite just stops rendering
Whenever I select it and try to move it, it moves less that 1 unit along the X and Y axis and then stops. For some reason, it deselects itself or stops moving before I let go of the mouse. I don't know why this would be since the only way to deselect an object is by letting go of the mouse.
This is a unity2D project BTW, and this script is the backbone of the game I'm making. Please help!
thanks.
I understand tf as a character which is needed to move.
According to the OnMouseDown function,
OnMouseDown is called when the user has pressed the mouse button while over the Collider.
Doc Link here
You will require a background and script may attach to it. Get the mouse position from background. Than set the position to the tf(character). 2D game z position always should be 0.
And of course, you can change the size of the background as large as you need.
Image and script can explain better.
Here is GoToMouse.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GoToMouse : MonoBehaviour
{
public Transform tf;
private bool Selected = false;
// Start is called before the first frame update
void Start()
{
// the tf is drag and drop from unity
//tf = GetComponent<Transform>();
}
private void OnMouseDown()
{
if (Selected == false)
{
Selected = true;
}
if (Selected == true)
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
tf.position = new Vector3(mousePos.x,mousePos.y,tf.position.z); // notice the tf.position.z
}
}
private void OnMouseUp()
{
if (Selected == true)
{
Selected = false;
}
}
}
I ended up figuring it out, I'm not sure what I was doing wrong but this new script seems to work great. Here's the script for people who want to plagiarize.
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
public class MoveTowards : MonoBehaviour
{
private Rigidbody2D rb;
public float force = 1f;
private bool selected = false;
public void Awake()
{
//Get rigidbody from the gameobject this script is attatched to
rb = GetComponent<Rigidbody2D>();
}
public void OnMouseDown()
{
//become selected when clicked
selected = true;
}
public void OnMouseUp()
{
//become deselected when you let go of left click
selected = false;
}
void Update()
{
if (selected == true)
{
//move towards mouse if selected
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 dir = (mousePos - transform.position);
dir.z = 0.0f;
Vector3 dirNormalized = dir.normalized;
Vector2 relativePos = mousePos - gameObject.transform.position;
rb.AddForce(relativePos * force);
}
}
}

How do i tell the camera to only follow the gameObject x orientation

Hello everyone beginner here, i am working on the moving vehicle challenge and i could make the camera follow the truck and also could make the camera switch between views (driver view/back view) the problem is when i switch to back view the initial x rotation for the camera is set to 0 so i want the camera to follow the player x orientation when in driver view so i don't lose the back view orientation, you can see my code below and the link for the project package here, Thank you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayer : MonoBehaviour
{
//Player GameObject variable (the vehicle)
public GameObject player;
//Fixing the camera vertical position
private Vector3 offset = new Vector3(0, 5, -7);
private Vector3 offset2 = new Vector3(0, 2.5f, 0.3f);
private int currentTarget;
public bool camController;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
camController = Input.GetButtonDown("Fire1");
if (camController) {
if (offset == offset2)
{
currentTarget = 2;
} else
{
currentTarget = 1;
}
switch(currentTarget)
{
case 1:
offset = offset2;
break;
case 2:
offset = new Vector3(0, 5, -7);
break;
}
}
//Offset the camera behind the player by adding to the player's position
transform.position = player.transform.position + offset;
transform.rotation = player.transform.rotation;
Debug.Log(camController);
}
}
I think it would be easier to have multiple cameras and switch between them. So create your 2 cameras, add Parent Constraints
to them and set them up as you need. Then create a script which enables and disables the cameras like this:
using UnityEngine;
public class SwitchCams : MonoBehaviour
{
public GameObject cam1;
public GameObject cam2;
bool isCam1 = true;
void Start(){
cam1.SetActive(true);
cam1.SetActive(false);
}
void Update(){
bool shouldSwitch = Input.GetButtonDown("Fire1");
if(shouldSwitch){
isCam1 = !isCam1;
cam1.SetActive(isCam1);
cam2.SetActive(!isCam1);
}
}
}
For some reason in unity the easiest way to switch between cameras is to enable and disable them. So this script just does that.
Remember to drag your cameras into the slots cam1 and cam2 of the script in the inspector.

Move camera with button in unity

I want move Main Camera with button. Its my game play :
its my scene:
want when click in button, main camera move to right in another pic.
This is my script for button:
public void Uss(GameObject camera) {
Vector3 temp = transform.position;
temp.x += 0.1f;
camera.transform.position = temp;
}
In your script, the button is moved, not the camera. You should move the GameObject of the main camera instead.
Transform cameraTransform;
void Start()
{
cameraTransform = Camera.main.gameObject.transform;
}
public void Update()
{
cameraTransform.Translate(7, 0, 0);
}
But I recommend you write the logic in the onClick handler of the button like below.
Attach a script to the button GameObject
float step = 100;//find a proper value for this
void Start()
{
Button b = gameObject.GetComponent<Button>();
b.onClick.AddListener(
()=>
{
Camera.main.gameObject.transform.Translate(step, 0, 0);
}
);
}
The step value is dependent on the size of your pictures.
I haven't tested the script but it should work in that way.

Spawning in Unity: Spheres flying out of range

I am programming a game in Unity. I am trying to spawn a sphere in space everytime the user clicks the interface. I can spawn the spheres, but the spheres are always at coordinates of around (200,200, 0) and (400,400,0), but the spheres should be spawned at where the pointer is on the screen. It's my code below, can someone help? I am writing in C#:
using UnityEngine;
using System.Collections;
public class myscript : MonoBehaviour {
//initialize a circle
public GameObject Node;
public float cooldown = 1;
bool clicker;
float clicktime = 0;
GameObject node; //reference to the prefab
// Use this for initialization
void Start () {
}
//In everyframe you can
void Update () {
clicker = Input.GetMouseButtonDown(0); //obtaining the input
clicktime += Time.deltaTime;
}
//Check whether you can shoot
void FixedUpdate(){
if (clicker == true && clicktime >= cooldown) { //if the clicker is clicked and the previos clicking is done
SpawnCircle(); //spawn a circle
clicktime = 0; //reset timer
}
}
void SpawnCircle(){
//this creates a new game object
x = Input.mousePosition.x
y = Input.mousePosition.
node = GameObject.Instantiate (Node,Input.mousePosition,Quaternion.identity) as GameObject;
//settings that we initalize our object with
//node.transform.position = new Vector3(Input.mousePosition.x, Input.mousePosition.y,0);
}
}
You need to calculate ScreenToWorld Coordinates. With Unity it's easy actually.
https://unity3d.com/learn/tutorials/modules/beginner/physics/raycasting

Android Controller for Unity game

I was making game in Unity 3D
and used the one click converter of unity to convert it in Android .apk
The game is opening in Android phone
but the player is not moving
Player controller Script:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public Vector2 moving = new Vector2();
public int Bulletlimit = 0;
public int MaxBulletlimit = 3;
public bool Gun;
private float lastShotTime ;
public float fireDelay = 0.2f;
public Transform BulletDirection;
public Bullet bullet;
// Use this for initialization
void Start () {
lastShotTime = Time.time;
}
// Update is called once per frame
void Update () {
moving.x = moving.y = 0;
if (Input.GetKey ("right")) {
moving.x = 1;
} else if (Input.GetKey ("left")) {
moving.x = -1;
}
if (Input.GetKey ("up")) {
moving.y = 1;
} else if (Input.GetKey ("down")) {
moving.y = -1;
}
if (Input.GetKey ("s")) {
if(Gun){
if(Bulletlimit < MaxBulletlimit)
{
if(Time.time > lastShotTime + fireDelay)
{
Bullet clone = Instantiate (bullet, BulletDirection.position, Quaternion.identity) as Bullet;
Bulletlimit = Bulletlimit + 1;
lastShotTime = Time.time;
}
}
}
}
}
public void BulletCount()
{
Bulletlimit = Bulletlimit - 1;
}
}
How do I make him move in touch screens?
Your code is based on keystrokes - that (probably) wont apply to your touch screen.
There are a few ways you could do this, for something so simple I would probably try adding a Canvas along with some buttons to act as controls.
From there you can use the OnMouseDown()/OnMouseUp()/OnClick() methods (This also converts to touchscreens) instead of keystrokes.
How you code from there is a choice you have to make but in this case I would likely use the buttons to turn on/off movement bools and check/apply them in the Update() method.
If you're unsure of how to use the new unity UI try this...
https://unity3d.com/learn/tutorials/modules/beginner/ui/ui-canvas
If you're running the new version of unity (currently 5.1 I believe), my editor looks different to the tutorials and won't stay as default for some reason. Simply set the editor/inspector view to default if some of the options appear to be missing.
There are more complex things you can do with the actual touch inputs but I don't think you need to worry about it in this particular case.
Hope this helps :)

Categories