Hello, I’m making a 2D game for Android, right now it’s really simple but yet it feels laggy when creating a build. I’ve followed a few tutorials, lowered quality, etc. but I feel like I’m missing something.
This is my code for moving my character (you can drag and shoot something like Angry Birds):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Controls : MonoBehaviour
{
public float power = 10f;
public float maxDrag = 5f;
public Rigidbody2D rb;
public LineRenderer lr;
public SpriteRenderer sr;
public AudioClip audioclip;
public int jumps = 1;
Vector3 dragStartPos;
Touch touch;
private void Start(){
rb.velocity = new Vector2(0.0f, 0.0f);
Time.timeScale = 0;
}
private void Update()
{
if(jumps >= 1){
sr.color = new Color(0.9433962f, 0.493948f, 0.943103f, 1f);
if(Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
DragStart();
}
if (touch.phase == TouchPhase.Moved)
{
Dragging();
}
if (touch.phase == TouchPhase.Ended)
{
DragRealease();
}
}
}
if(jumps == 0){
sr.color = new Color(1f, 1f, 1f, 1f);
}
}
private void OnTriggerEnter2D(Collider2D other){
if(other.CompareTag("Surface")){
Vector3 playerPos=other.transform.position;
rb.velocity = new Vector2(0.0f, 0.0f);
rb.gravityScale = 1f;
Debug.Log(playerPos.x);
jumps = 1;
ScoreScript.scoreValue+=1;
}
if(other.CompareTag("Finish")){
//SceneManager.LoadScene("GameOver");
jumps=1;
GetComponent<AudioSource>().clip = audioclip;
GetComponent<AudioSource>().Play();
}
if (other.CompareTag("Coin")){
//coins.coinsvalue+=1;
Destroy(other.gameObject);
}
if (other.CompareTag("Win"))
{
if (changer.canwin)
{
SceneManager.LoadScene("Win");
ScoreScript.scoreValue = 0;
//coins.coinsvalue = 0;
} /*else
{
SceneManager.LoadScene("GameOver");
ScoreScript.scoreValue = 0;
JUMPS.jumpsleft = 1;
coins.coinsvalue = 0;
}*/
}
}
private void DragStart()
{
dragStartPos = Camera.main.ScreenToWorldPoint(touch.position);
dragStartPos.z = 0f;
lr.positionCount = 1;
lr.SetPosition(0, dragStartPos);
}
private void Dragging()
{
Vector3 draggingPos = Camera.main.ScreenToWorldPoint(touch.position);
dragStartPos.z = 0f;
lr.positionCount = 2;
lr.SetPosition(1, draggingPos);
}
private void DragRealease()
{
Time.timeScale = 1;
lr.positionCount = 0;
Vector3 dragReleasePos = Camera.main.ScreenToWorldPoint(touch.position);
dragStartPos.z = 0f;
Vector3 force = dragStartPos - dragReleasePos;
Vector3 clampedForce = Vector3.ClampMagnitude(force, maxDrag) * power;
rb.AddForce(clampedForce, ForceMode2D.Impulse);
jumps = 0;
}
}
I’ve read that I should do transforms and etc. in FixedUpdate instead of Update but when I tried to, the game would instantly freeze, not allowing to play.