Hello,
So I have 2d shooter game, I am currently trying to make it mobilize it and I ran into a problem when after I shoot and let go (on my iPad) of the screen the cursor snaps back to where it started. Does anyone know how to fix this?
Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Weapon : MonoBehaviour {
public GameObject projectile;
public Transform shotPoint;
public float timeBetweenShots;
private float shotTime;
Animator cameraAnim;
private void Start() {
cameraAnim = Camera.main.GetComponent<Animator>();
}
private void Update() {
Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle - 90f, Vector3.forward);
transform.rotation = rotation;
if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space)) {
if(Time.time >= shotTime) {
Instantiate(projectile, shotPoint.position, transform.rotation);
cameraAnim.SetTrigger("shake");
shotTime = Time.time + timeBetweenShots;
}
}
}
}
I don’t think the code snippet you’ve shared here has anything to do with the cursor, except maybe reading its position to determine where to shoot. Mind sharing the script that deals with the touch input and determining the cursor position?
Well there’s nothing in that script that seems to move anything. There is also no code that responds to any touching and dragging. The only thing I see here is:
rotating the object to face some “shotPoint”
instantiating a projectile facing towards that shotPoint when the left mouse button is clicked (I believe that will also detect touchscreen taps).
I presume that the “shotPoint” is the cursor that we’re discussing, and the movement of that object is certainly not handled in this script.
Maybe look at that shotPoint object and see if there are any scripts on it?
Shot point is just where the projectile instantiates at, nothing to do with that. So how exactly can I make it so it wont snap back to where it started?
Ok so is it a GameObject? Or is it literally just the hardware cursor, the image for which you’ve changed?
If it’s the hardware cursor, I’m not sure there’s much you can do. It’s probably just a quirk of how your particular device handles the cursor, which may be to return it to the center when you release your finger. I would suggest using a “virtual” cursor instead by creating a GameObject with a SpriteRenderer and moving it around based on where the touch position is.
I think the problem is that you’re just blankly using Input.mousePosition. that obviously won’t return anything sensible if your finger isn’t touching the screen.
You’ll need to use the actual touch input stuff. Start here: