In this game what I'm trying to accomplish is a sprite that rotates towards the touch position (which I have done) and have knock-back. The problem i have run into now is that it rotates if you hold your finger down on your screen. I'm trying to make it so that it only rotates and applies force to the initial touch position, and if they want to change that position for the user to take off his finger and touch somewhere else.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TouchMove : MonoBehaviour
{
public float speed = 100;
public Transform ttouch;
public Rigidbody2D myRigidbody;
public float knock = 40;
// Start is called before the first frame update
void Start()
{
knock = knock * -1;
}
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
ttouch.position = touchPosition;
Rotate();
Knockback();
}
}
void Rotate() {
//Rotate towards touch
Vector3 direction = ttouch.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, speed * Time.deltaTime);
}
void Knockback() {
//Knock back applied when screen touched
myRigidbody.AddForce(transform.right * knock);
}
}
↧