Unity 2D code repeating in phone but not trouble in pc - c#

I make an game 2D in Unity. My game looks different on the phone. I would the gameobject come to the scene episodic. When I test it on the computer, there is not trouble. But when I test on the phone, the process is repeating.
Code :
for(kacxgiti = 0; kacxgiti < 91; kacxgiti++){
        karbayv = karbay.transform.position;
    if(kacxgiti < 90){
    karbay.transform.position = new Vector3(karbayv.x - 0.1f, karbayv.y, karbayv.z);
    kacxgiti = kacxgiti + 1;
    yield return new WaitForSeconds(0.05f);
    }else{
    kamyongel();
    }
        }
Full Code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using GoogleMobileAds.Api;
using System;
public class karhareket : MonoBehaviour
{
public GameObject karbay;
Vector3 karbayv;
int kacxgiti;
public static int kamyongeli, kamyongidi;
public GameObject kamyon;
Vector3 kamyonv, kamyonvv;
int kamyonxgiti;
int kamyoncikari;
public Button subebtn;
public Text guntext;
int guni, gunfonti, gunbuyuti, kardurduri;
public Sprite[] musteris;
int musterigeli, musterixgel, mustericikari;
public GameObject musteri;
Vector3 musteriv, musterivv;
public Text paratext;
string gecisid;
InterstitialAd gecisreklam;
int ilkgunyazii;
// Start is called before the first frame update
void Start()
{
ilkgunyazii = 1;
gecisid = "ca-app-pub-6761789303172472/5658205887";
this.gecisreklam = new InterstitialAd(gecisid);
AdRequest request = new AdRequest.Builder().Build();
this.gecisreklam.LoadAd(request);
this.gecisreklam.OnAdClosed += reklamkapatinca;
this.gecisreklam.OnAdFailedToLoad += reklamkapatinca;
if(PlayerPrefs.HasKey("para")){
paratext.text = PlayerPrefs.GetInt("para") + "$";
}else{
PlayerPrefs.SetInt("para", 100);
PlayerPrefs.Save();
paratext.text = "100$";
}
kamyongeli = 1;
kamyoncikari = 0;
kardurduri = 0;
musterigeli = 1;
if(PlayerPrefs.GetInt("mustericikar") == 1){
ilkgunyazii = 0;
guntext.text = "";
musteri.GetComponent<SpriteRenderer>().sprite = musteris[PlayerPrefs.GetInt("musteriid")];
PlayerPrefs.DeleteKey("musteriid");
PlayerPrefs.DeleteKey("mustericikar");
kamyon.gameObject.SetActive(false);
musterigeli = 0;
kamyongeli = 0;
kardurduri = 1;
guntext.gameObject.SetActive(false);
musterigidivergari();
}
while(kamyongidi == 1 || PlayerPrefs.GetInt("kamyoncikar") == 1){
int musterid = UnityEngine.Random.Range(0, 20);
musteri.GetComponent<SpriteRenderer>().sprite = musteris[musterid];
PlayerPrefs.SetInt("musteriid", musterid);
PlayerPrefs.Save();
ilkgunyazii = 0;
PlayerPrefs.DeleteKey("kamyoncikar");
kamyongeli = 0;
kardurduri = 1;
kamyongidivergari();
guntext.gameObject.SetActive(false);
//gun ve karakter ilerleme olmasın
break;
}
if(kardurduri == 0){
kamyongeli = 0;
karbayv = karbay.transform.position;
//InvokeRepeating("pozisyonayarla", 0, 0.05f);
for(kacxgiti = 0; kacxgiti < 91; kacxgiti++){
karbayv = karbay.transform.position;
if(kacxgiti < 90){
karbay.transform.position = new Vector3(karbayv.x - 0.1f, karbayv.y, karbayv.z);
karbayv = new Vector3(karbayv.x - 0.1f, karbayv.y, karbayv.z);
kacxgiti = kacxgiti + 1;
yield return new WaitForSeconds(0.05f);
}else{
kamyongelivergari();
break;
}
}
}else{
karbay.transform.position = new Vector3(-4, -1, 0);
}
while(kamyongeli == 1){
InvokeRepeating("kamyongelsin", 0, 0.03f);
break;
}
subebtn.onClick.AddListener(subetik);
if(PlayerPrefs.HasKey("gun")){
guni = PlayerPrefs.GetInt("gun");
}else{
PlayerPrefs.SetInt("gun", 1);
PlayerPrefs.Save();
guni = 1;
}
if(ilkgunyazii == 1){
gunfonti = 20;
gunbuyuti = 1;
guntext.text = "Day " + guni.ToString();
InvokeRepeating("guntextayarla", 0, 0.02f);
}
}
void guntextayarla(){
if(gunbuyuti == 0){
guntext.fontSize = gunfonti;
gunfonti--;
}else if(gunbuyuti == 1){
guntext.fontSize = gunfonti;
gunfonti++;
if(gunfonti == 61){
gunbuyuti = 0;
}
}
}
void musterigelsin(){
musteriv = musteri.transform.position;
if(musterixgel < 145){
musteri.transform.position = new Vector3(musteriv.x - 0.1f, musteriv.y, musteriv.z);
musterixgel++;
}else{
musterigeli = 0;
SceneManager.LoadScene("malsat");
}
}
void musterigitsin(){
musterivv = musteri.transform.position;
if(mustericikari < 575){
musteri.transform.position = new Vector3(musterivv.x - 0.1f, musterivv.y, musterivv.z);
mustericikari++;
if(mustericikari == 165){
gunbittiyaziayarla();
}
}
}
void kamyongelivergari(){
//CancelInvoke("pozisyonayarla");
kamyongeli = 1;
//kardurduri = 1;
InvokeRepeating("kamyongelsin", 0, 0.05f);
}
void reklamgoster(){
if(gecisreklam.IsLoaded()){
gecisreklam.Show();
}else{
reklamkapatincaa();
}
}
public void reklamkapatinca(object sender, EventArgs args){
SceneManager.LoadScene("manav");
}
public void reklamkapatincaa(){
SceneManager.LoadScene("manav");
}
void gunbittextayarla(){
if(gunbuyuti == 0){
guntext.fontSize = gunfonti;
gunfonti--;
}else if(gunbuyuti == 1){
guntext.fontSize = gunfonti;
gunfonti++;
if(gunfonti == 41){
gunbuyuti = 0;
PlayerPrefs.SetInt("gun", PlayerPrefs.GetInt("gun") + 1);
PlayerPrefs.Save();
reklamgoster();
CancelInvoke("gunbittextayarla");
}
}
}
void gunbittiyaziayarla(){
guntext.text = "Day " + PlayerPrefs.GetInt("gun") + " Finished";
guntext.gameObject.SetActive(true);
guntext.text = "Day " + PlayerPrefs.GetInt("gun") + " Finished";
gunfonti = 20;
gunbuyuti = 1;
InvokeRepeating("gunbittextayarla", 0, 0.02f);
}
void subetik(){
SceneManager.LoadScene("subeler");
}
void pozisyonayarla(){
karbayv = karbay.transform.position;
if(kacxgiti < 90){
karbay.transform.position = new Vector3(karbayv.x - 0.1f, karbayv.y, karbayv.z);
kacxgiti++;
}else{
kamyongelivergari();
}
}
void kamyongelsin(){
kamyonv = kamyon.transform.position;
if(kamyonxgiti < 125){
kamyon.transform.position = new Vector3(kamyonv.x - 0.1f, kamyonv.y, kamyonv.z);
kamyonxgiti++;
}else{
kamyongeli = 0;
SceneManager.LoadScene("malal");
CancelInvoke("kamyongelsin");
}
}
void kamyongitsin(){
kamyongidi = 0;
kamyonvv = kamyon.transform.position;
if(kamyoncikari < 300){
kamyon.transform.position = new Vector3(kamyonvv.x - 0.1f, kamyonvv.y, kamyonvv.z);
kamyoncikari++;
if(kamyoncikari == 150){
Debug.Log("geldi");
musterigelivergari();
}
}else{
CancelInvoke("kamyongitsin");
}
}
void musterigelivergari(){
InvokeRepeating("musterigelsin", 0, 0.03f);
}
void musterigidivergari(){
musteri.transform.position = new Vector3(0f, -1.9f, 0f);
InvokeRepeating("musterigitsin", 0, 0.05f);
}
void kamyongidivergari(){
kamyon.transform.position = new Vector3(0f, -3f, kamyon.transform.position.z);
InvokeRepeating("kamyongitsin", 0, 0.05f);
}
//kamyongidi 1 olunca kamyonu gönder
// Update is called once per frame
void Update()
{
/*if(kamyongeli == 1){
InvokeRepeating("kamyongelsin", 0, 0.05f);
}*/
/*if(kamyongidi == 1 || PlayerPrefs.GetInt("kamyoncikar") == 1){
kamyongeli = 0;
kamyongidivergari();
PlayerPrefs.SetInt("kamyoncikar", 0);
PlayerPrefs.Save();
//kamyongidi = 0;
}else if(kamyongeli == 1){
InvokeRepeating("kamyongelsin", 0, 0.05f);
kamyongeli = 0;
}*/
}
}
In pc :
https://drive.google.com/file/d/1IaOMyP4bzOopaQCjBtOBV-KBYBflIB_f/view?usp=drivesdk
In phone :
https://drive.google.com/file/d/1IcPNvg7OjCerzFKc8M12LrO8B-BKyWUC/view?usp=drivesdk
How I can resolve this problem?

Related

How to Get Image Pixel with its texture position in scene and Place with another texture pixel by pixel

I have 5 different sprites having same Rect.
I create canvas Image and pass sprite to it. I want to get the pixel of that image according to texture size not to the canvas size or screen size through mouse position.
After accessing that position I can change that pixel to another sprite pixel having same rect.
I am working on it. But issue is that I have 2 sprites having resolution of 1080 x 1920. It works only that resolution but when I change the resolution it does not work correctly because resolution of sprite and canvas are different and mouse position values changes according to canvas resolution and sprite resolution is fixed. How I can do this. Anyone know the solution please tell me.
I give you the working script.
public class MaskControl : MonoBehaviour, IPointerDownHandler {
private void Awake()
{
if (instance == null)
instance = this;
DifferenceMultiplyer = this.ScreenReferance.y / (float)Screen.height;
}
private void Start()
{
//this.PlaceTexture(this.TargetTexture);
}
public void OnPointerDown(PointerEventData eventData)
{
Drawn = false;
canDraw = true;
}
private void Update()
{
if (!this.canDraw)
{
return;
}
if (Input.GetMouseButton(0))
{
/*if (Varf != this.Varf)
{
init(this.Varf);
}*/
//Vector2 pos = Camera.main.WorldToScreenPoint(this.Varf.position);
//Vector2 val = Input.mousePosition / canvas.scaleFactor;
//this.VarfPos = this.Varf.position;
//this.VarfPos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
this.PixelAdress = Input.mousePosition;
//this.PixelAdress = new Vector2(this.VarfPos.x * this.DifferenceMultiplyer + (this.ScreenReferance.x - (float)Screen.width * this.DifferenceMultiplyer) / 2f, this.VarfPos.y * this.DifferenceMultiplyer);
//this.PixelAdress = new Vector2(this.VarfPos.x * this.DifferenceMultiplyer , this.VarfPos.y * this.DifferenceMultiplyer);
/*if (SceneManager.GetActiveScene().name == "Nails" && NailManager.instance.RightHand.activeSelf)
{
this.PixelAdress = new Vector2(-this.PixelAdress.x, this.PixelAdress.y);
}*/
Debug.Log(DifferenceMultiplyer + " "+this.PixelAdress + " "+ Input.mousePosition);
if (!this.drawAlpha)
{
this.Circle(this.TargetTexture, (int)this.PixelAdress.x, (int)this.PixelAdress.y, this.BrushSize, true);
}
else
{
this.Circle(this.TargetTexture, (int)this.PixelAdress.x, (int)this.PixelAdress.y, this.BrushSize, false);
}
}
if (Input.GetMouseButtonUp(0))
{
this.canDraw = false;
this.drawAlpha = false;
}
}
public void ResetDraw()
{
this.SourceTexture = null;
SourceTextureColors = null;
DrawTexture = null;
TargetTextureColors = null;
}
public void init(Transform varf)
{
this.Varf = varf;
this.canDraw = true;
this.InitializeDraw(Change_sp.texture, TargetImage, this.Varf, 40, false);
}
public void InitializeDraw(Texture2D sourceTexture, Image targetImage, Transform varf, int brushSize, bool forced = false)
{
UnityEngine.Debug.Log("start to initialize draw");
this.BrushSize = brushSize;
this.Varf = varf;
if (this.SourceTexture != null && !forced && sourceTexture.name == this.SourceTexture.name)
{
if (targetImage.name == this.TargetImage.name)
{
return;
}
}
this.SourceTexture = sourceTexture;
this.TargetImage = targetImage;
this.TargetTexture = new Texture2D(sourceTexture.width, sourceTexture.height, TextureFormat.ARGB32, false);
if (DrawTexture == null)
{
this.TargetImage.gameObject.SetActive(true);
if (targetImage.sprite == null)
{
Color32[] pixels = this.TargetTexture.GetPixels32();
for (int i = 0; i < pixels.Length; i++)
{
pixels[i] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, 1);
}
this.TargetTexture.SetPixels32(pixels);
this.TargetTexture.Apply();
this.TargetImage.sprite = Sprite.Create(this.TargetTexture, new Rect(0f, 0f, (float)sourceTexture.width, (float)sourceTexture.height), Vector2.zero);
}
else
{
Color32[] pixels2 = targetImage.sprite.texture.GetPixels32();
for (int j = 0; j < pixels2.Length; j++)
{
if (pixels2[j].a == 0)
{
pixels2[j] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, 1);
}
}
this.TargetTexture.SetPixels32(pixels2);
this.TargetTexture.Apply();
this.TargetImage.sprite = Sprite.Create(this.TargetTexture, new Rect(0f, 0f, (float)sourceTexture.width, (float)sourceTexture.height), Vector2.zero);
targetImage.sprite.texture.Apply();
}
DrawTexture = this.TargetTexture;
}
else
{
Color32[] pixels3 = DrawTexture.GetPixels32();
for (int k = 0; k < pixels3.Length; k++)
{
if (pixels3[k].a == 0)
{
pixels3[k] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, 1);
}
}
this.TargetTexture.SetPixels32(pixels3);
this.TargetTexture.Apply();
this.TargetImage.sprite = Sprite.Create(this.TargetTexture, new Rect(0f, 0f, (float)sourceTexture.width, (float)sourceTexture.height), Vector2.zero);
}
this.TargetTextureColors = this.TargetTexture.GetPixels32();
this.SourceTextureColors = sourceTexture.GetPixels32();
}
public void Circle(Texture2D tex, int cx, int cy, int r, bool draw)
{
for (int i = 0; i <= r; i++)
{
int num = (int)Mathf.Ceil(Mathf.Sqrt((float)(r * r - i * i)));
for (int j = 0; j <= num; j++)
{
int num2 = cx + i;
int num3 = cx - i;
int num4 = cy + j;
int num5 = cy - j;
Debug.Log(num2 + " " + tex.width + " " + num4 + " "+ byte.MaxValue);
if (draw)
{
if (num4 * tex.width + num2 < this.SourceTextureColors.Length)
{
this.TargetTextureColors[num4 * tex.width + num2] = this.SourceTextureColors[num4 * tex.width + num2];
}
}
else
{
this.TargetTextureColors[num4 * tex.width + num2] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, 1);
}
if (draw)
{
if (num4 * tex.width + num3 < this.SourceTextureColors.Length)
{
this.TargetTextureColors[num4 * tex.width + num3] = this.SourceTextureColors[num4 * tex.width + num3];
}
}
else
{
this.TargetTextureColors[num4 * tex.width + num3] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, 1);
}
if (draw)
{
if (num5 * tex.width + num2 < this.SourceTextureColors.Length)
{
this.TargetTextureColors[num5 * tex.width + num2] = this.SourceTextureColors[num5 * tex.width + num2];
}
}
else
{
this.TargetTextureColors[num5 * tex.width + num2] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, 1);
}
if (draw)
{
if (num5 * tex.width + num3 < this.SourceTextureColors.Length)
{
this.TargetTextureColors[num5 * tex.width + num3] = this.SourceTextureColors[num5 * tex.width + num3];
}
}
else
{
this.TargetTextureColors[num5 * tex.width + num3] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, 1);
}
if (!this.Drawn && draw)
{
if (this.SourceTextureColors[num4 * tex.width + num2].a != 0)
{
this.Drawn = true;
}
else if (this.SourceTextureColors[num4 * tex.width + num3].a != 0)
{
this.Drawn = true;
}
else if (this.SourceTextureColors[num5 * tex.width + num2].a != 0)
{
this.Drawn = true;
}
else if (this.SourceTextureColors[num5 * tex.width + num3].a != 0)
{
this.Drawn = true;
}
}
}
}
tex.SetPixels32(this.TargetTextureColors);
tex.Apply();
}
public static MaskControl instance;
public Sprite Change_sp;
public Image TargetImage;
public Texture2D SourceTexture;
public Texture2D TargetTexture;
[Header("```````````````````````")]
public Transform Varf;
private Color32[] SourceTextureColors;
private Color32[] TargetTextureColors;
private float DifferenceMultiplyer;
public Vector2 ScreenReferance;
private Vector2 PixelAdress;
public Texture2D DrawTexture;
public int BrushSize;
public bool canDraw;
public bool drawAlpha;
public bool Drawn;
public Vector2 VarfPos;
}

Refactored a script in order to understand it but I'm now experiencing a bug I can't seem to solve

I've been playing around with trying to do an active ragdoll when I came across a script that Youtube user MetalCore999 had created (First script below). I tried refactoring this code so that I would understand what he had done to make this work, and eventually improving upon it myself however I've hit a brick wall and cannot seem to figure out what I'm doing wrong.
The problem that I am experiencing is that in the original script by MetalCore999, the character stands up on its own when there is no input, however in my version of the script the character decides to just squat down.
I've tried reading through each element and checking if there is some piece of code that is not being called properly but I cannot for the life of me figure out where this bug is at.
Here is the original script by MetalCore999:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Example : MonoBehaviour
{
public GameObject[] PlayerParts;
public ConfigurableJoint[] JointParts;
Vector3 COM;
public float TouchForce, TimeStep, LegsHeight, FallFactor;
float Step_R_Time, Step_L_Time;
public bool StepR, StepL, WalkF, WalkB, Falling, Fall, StandUp;
bool flag, Flag_Leg_R, Flag_Leg_L;
Quaternion StartLegR1, StartLegR2, StartLegL1, StartLegL2;
JointDrive Spring0, Spring150, Spring300, Spring320;
private void Awake()
{
Physics.IgnoreCollision(PlayerParts[2].GetComponent<Collider>(), PlayerParts[4].GetComponent<Collider>(), true);
Physics.IgnoreCollision(PlayerParts[3].GetComponent<Collider>(), PlayerParts[7].GetComponent<Collider>(), true);
StartLegR1 = PlayerParts[4].GetComponent<ConfigurableJoint>().targetRotation;
StartLegR2 = PlayerParts[5].GetComponent<ConfigurableJoint>().targetRotation;
StartLegL1 = PlayerParts[7].GetComponent<ConfigurableJoint>().targetRotation;
StartLegL2 = PlayerParts[8].GetComponent<ConfigurableJoint>().targetRotation;
Spring0 = new JointDrive();
Spring0.positionSpring = 0;
Spring0.positionDamper = 0;
Spring0.maximumForce = Mathf.Infinity;
Spring150 = new JointDrive();
Spring150.positionSpring = 150;
Spring150.positionDamper = 0;
Spring150.maximumForce = Mathf.Infinity;
Spring300 = new JointDrive();
Spring300.positionSpring = 300;
Spring300.positionDamper = 100;
Spring300.maximumForce = Mathf.Infinity;
Spring320 = new JointDrive();
Spring320.positionSpring = 320;
Spring320.positionDamper = 0;
Spring320.maximumForce = Mathf.Infinity;
}
private void Update()
{
PlayerParts[12].transform.position = Vector3.Lerp(PlayerParts[12].transform.position, PlayerParts[2].transform.position, 2 * Time.unscaledDeltaTime);
#region Input
if (Input.GetKeyDown(KeyCode.UpArrow))
{
PlayerParts[0].GetComponent<Rigidbody>().AddForce(Vector3.back * TouchForce, ForceMode.Impulse);
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
PlayerParts[0].GetComponent<Rigidbody>().AddForce(Vector3.forward * TouchForce, ForceMode.Impulse);
}
if (Input.GetKeyDown(KeyCode.Space))
Application.LoadLevel(Application.loadedLevel);
if (Input.GetKeyDown(KeyCode.S))
{
if (Time.timeScale == 1)
Time.timeScale = 0.4f;
else
Time.timeScale = 1;
}
#endregion
Calculate_COM();
PlayerParts[10].transform.position = COM;
Balance();
PlayerParts[11].transform.LookAt(PlayerParts[10].transform.position);
if (!WalkF && !WalkB)
{
StepR = false;
StepL = false;
Step_R_Time = 0;
Step_L_Time = 0;
Flag_Leg_R = false;
Flag_Leg_L = false;
JointParts[0].targetRotation = Quaternion.Lerp(JointParts[0].targetRotation, new Quaternion(-0.1f, JointParts[0].targetRotation.y, JointParts[0].targetRotation.z, JointParts[0].targetRotation.w), 6 * Time.fixedDeltaTime);
}
}
private void FixedUpdate()
{
LegsMoving();
}
void Balance()
{
if (PlayerParts[10].transform.position.z < PlayerParts[6].transform.position.z && PlayerParts[10].transform.position.z < PlayerParts[9].transform.position.z)
{
WalkB = true;
JointParts[0].targetRotation = Quaternion.Lerp(JointParts[0].targetRotation, new Quaternion(-0.1f, JointParts[0].targetRotation.y, JointParts[0].targetRotation.z, JointParts[0].targetRotation.w), 6 * Time.fixedDeltaTime);
}
else
{
WalkB = false;
}
if (PlayerParts[10].transform.position.z > PlayerParts[6].transform.position.z && PlayerParts[10].transform.position.z > PlayerParts[9].transform.position.z)
{
WalkF = true;
JointParts[0].targetRotation = Quaternion.Lerp(JointParts[0].targetRotation, new Quaternion(0, JointParts[0].targetRotation.y, JointParts[0].targetRotation.z, JointParts[0].targetRotation.w), 6 * Time.fixedDeltaTime);
}
else
{
WalkF = false;
}
if (PlayerParts[10].transform.position.z > PlayerParts[6].transform.position.z + FallFactor &&
PlayerParts[10].transform.position.z > PlayerParts[9].transform.position.z + FallFactor ||
PlayerParts[10].transform.position.z < PlayerParts[6].transform.position.z - (FallFactor + 0.2f) &&
PlayerParts[10].transform.position.z < PlayerParts[9].transform.position.z - (FallFactor + 0.2f))
{
Falling = true;
}
else
{
Falling = false;
}
if (Falling)
{
JointParts[1].angularXDrive = Spring0;
JointParts[1].angularYZDrive = Spring0;
LegsHeight = 5;
}
else
{
JointParts[1].angularXDrive = Spring300;
JointParts[1].angularYZDrive = Spring300;
LegsHeight = 1;
JointParts[2].targetRotation = Quaternion.Lerp(JointParts[2].targetRotation, new Quaternion(0, JointParts[2].targetRotation.y, JointParts[2].targetRotation.z, JointParts[2].targetRotation.w), 6 * Time.fixedDeltaTime);
JointParts[3].targetRotation = Quaternion.Lerp(JointParts[3].targetRotation, new Quaternion(0, JointParts[3].targetRotation.y, JointParts[3].targetRotation.z, JointParts[3].targetRotation.w), 6 * Time.fixedDeltaTime);
JointParts[2].angularXDrive = Spring0;
JointParts[2].angularYZDrive = Spring150;
JointParts[3].angularXDrive = Spring0;
JointParts[3].angularYZDrive = Spring150;
}
if (PlayerParts[0].transform.position.y - 0.1f <= PlayerParts[1].transform.position.y)
{
Fall = true;
}
else
{
Fall = false;
}
if (Fall)
{
JointParts[1].angularXDrive = Spring0;
JointParts[1].angularYZDrive = Spring0;
StandUping();
}
}
void LegsMoving()
{
if (WalkF)
{
if (PlayerParts[6].transform.position.z < PlayerParts[9].transform.position.z && !StepL && !Flag_Leg_R)
{
StepR = true;
Flag_Leg_R = true;
Flag_Leg_L = true;
}
if (PlayerParts[6].transform.position.z > PlayerParts[9].transform.position.z && !StepR && !Flag_Leg_L)
{
StepL = true;
Flag_Leg_L = true;
Flag_Leg_R = true;
}
}
if (WalkB)
{
if (PlayerParts[6].transform.position.z > PlayerParts[9].transform.position.z && !StepL && !Flag_Leg_R)
{
StepR = true;
Flag_Leg_R = true;
Flag_Leg_L = true;
}
if (PlayerParts[6].transform.position.z < PlayerParts[9].transform.position.z && !StepR && !Flag_Leg_L)
{
StepL = true;
Flag_Leg_L = true;
Flag_Leg_R = true;
}
}
if (StepR)
{
Step_R_Time += Time.fixedDeltaTime;
if (WalkF)
{
JointParts[4].targetRotation = new Quaternion(JointParts[4].targetRotation.x + 0.07f * LegsHeight, JointParts[4].targetRotation.y, JointParts[4].targetRotation.z, JointParts[4].targetRotation.w);
JointParts[5].targetRotation = new Quaternion(JointParts[5].targetRotation.x - 0.04f * LegsHeight * 2, JointParts[5].targetRotation.y, JointParts[5].targetRotation.z, JointParts[5].targetRotation.w);
JointParts[7].targetRotation = new Quaternion(JointParts[7].targetRotation.x - 0.02f * LegsHeight / 2, JointParts[7].targetRotation.y, JointParts[7].targetRotation.z, JointParts[7].targetRotation.w);
}
if (WalkB)
{
JointParts[4].targetRotation = new Quaternion(JointParts[4].targetRotation.x - 0.00f * LegsHeight, JointParts[4].targetRotation.y, JointParts[4].targetRotation.z, JointParts[4].targetRotation.w);
JointParts[5].targetRotation = new Quaternion(JointParts[5].targetRotation.x - 0.06f * LegsHeight * 2, JointParts[5].targetRotation.y, JointParts[5].targetRotation.z, JointParts[5].targetRotation.w);
JointParts[7].targetRotation = new Quaternion(JointParts[7].targetRotation.x + 0.02f * LegsHeight / 2, JointParts[7].targetRotation.y, JointParts[7].targetRotation.z, JointParts[7].targetRotation.w);
}
if (Step_R_Time > TimeStep)
{
Step_R_Time = 0;
StepR = false;
if (WalkB || WalkF)
{
StepL = true;
}
}
}
else
{
JointParts[4].targetRotation = Quaternion.Lerp(JointParts[4].targetRotation, StartLegR1, (8f) * Time.fixedDeltaTime);
JointParts[5].targetRotation = Quaternion.Lerp(JointParts[5].targetRotation, StartLegR2, (17f) * Time.fixedDeltaTime);
}
if (StepL)
{
Step_L_Time += Time.fixedDeltaTime;
if (WalkF)
{
JointParts[7].targetRotation = new Quaternion(JointParts[7].targetRotation.x + 0.07f * LegsHeight, JointParts[7].targetRotation.y, JointParts[7].targetRotation.z, JointParts[7].targetRotation.w);
JointParts[8].targetRotation = new Quaternion(JointParts[8].targetRotation.x - 0.04f * LegsHeight * 2, JointParts[8].targetRotation.y, JointParts[8].targetRotation.z, JointParts[8].targetRotation.w);
JointParts[4].targetRotation = new Quaternion(JointParts[4].targetRotation.x - 0.02f * LegsHeight / 2, JointParts[4].targetRotation.y, JointParts[4].targetRotation.z, JointParts[4].targetRotation.w);
}
if (WalkB)
{
JointParts[7].targetRotation = new Quaternion(JointParts[7].targetRotation.x - 0.00f * LegsHeight, JointParts[7].targetRotation.y, JointParts[7].targetRotation.z, JointParts[7].targetRotation.w);
JointParts[8].targetRotation = new Quaternion(JointParts[8].targetRotation.x - 0.06f * LegsHeight * 2, JointParts[8].targetRotation.y, JointParts[8].targetRotation.z, JointParts[8].targetRotation.w);
JointParts[4].targetRotation = new Quaternion(JointParts[4].targetRotation.x + 0.02f * LegsHeight / 2, JointParts[4].targetRotation.y, JointParts[4].targetRotation.z, JointParts[4].targetRotation.w);
}
if (Step_L_Time > TimeStep)
{
Step_L_Time = 0;
StepL = false;
if (WalkB || WalkF)
{
StepR = true;
}
}
}
else
{
JointParts[7].targetRotation = Quaternion.Lerp(JointParts[7].targetRotation, StartLegL1, (8) * Time.fixedDeltaTime);
JointParts[8].targetRotation = Quaternion.Lerp(JointParts[8].targetRotation, StartLegL2, (17) * Time.fixedDeltaTime);
}
}
void StandUping()
{
if (WalkF)
{
JointParts[2].angularXDrive = Spring320;
JointParts[2].angularYZDrive = Spring320;
JointParts[3].angularXDrive = Spring320;
JointParts[3].angularYZDrive = Spring320;
JointParts[0].targetRotation = Quaternion.Lerp(JointParts[0].targetRotation, new Quaternion(-0.1f, JointParts[0].targetRotation.y,
JointParts[0].targetRotation.z, JointParts[0].targetRotation.w), 6 * Time.fixedDeltaTime);
if (JointParts[2].targetRotation.x < 1.7f)
{
JointParts[2].targetRotation = new Quaternion(JointParts[2].targetRotation.x + 0.07f, JointParts[2].targetRotation.y,
JointParts[2].targetRotation.z, JointParts[2].targetRotation.w);
}
if (JointParts[3].targetRotation.x < 1.7f)
{
JointParts[3].targetRotation = new Quaternion(JointParts[3].targetRotation.x + 0.07f, JointParts[3].targetRotation.y,
JointParts[3].targetRotation.z, JointParts[3].targetRotation.w);
}
}
if (WalkB)
{
JointParts[2].angularXDrive = Spring320;
JointParts[2].angularYZDrive = Spring320;
JointParts[3].angularXDrive = Spring320;
JointParts[3].angularYZDrive = Spring320;
if (JointParts[2].targetRotation.x > -1.7f)
{
JointParts[2].targetRotation = new Quaternion(JointParts[2].targetRotation.x - 0.09f, JointParts[2].targetRotation.y,
JointParts[2].targetRotation.z, JointParts[2].targetRotation.w);
}
if (JointParts[3].targetRotation.x > -1.7f)
{
JointParts[3].targetRotation = new Quaternion(JointParts[3].targetRotation.x - 0.09f, JointParts[3].targetRotation.y,
JointParts[3].targetRotation.z, JointParts[3].targetRotation.w);
}
}
}
void Calculate_COM()
{
COM = (JointParts[0].GetComponent<Rigidbody>().mass * JointParts[0].transform.position +
JointParts[1].GetComponent<Rigidbody>().mass * JointParts[1].transform.position +
JointParts[2].GetComponent<Rigidbody>().mass * JointParts[2].transform.position +
JointParts[3].GetComponent<Rigidbody>().mass * JointParts[3].transform.position +
JointParts[4].GetComponent<Rigidbody>().mass * JointParts[4].transform.position +
JointParts[5].GetComponent<Rigidbody>().mass * JointParts[5].transform.position +
JointParts[6].GetComponent<Rigidbody>().mass * JointParts[6].transform.position +
JointParts[7].GetComponent<Rigidbody>().mass * JointParts[7].transform.position +
JointParts[8].GetComponent<Rigidbody>().mass * JointParts[8].transform.position +
JointParts[9].GetComponent<Rigidbody>().mass * JointParts[9].transform.position) /
(JointParts[0].GetComponent<Rigidbody>().mass + JointParts[1].GetComponent<Rigidbody>().mass +
JointParts[2].GetComponent<Rigidbody>().mass + JointParts[3].GetComponent<Rigidbody>().mass +
JointParts[4].GetComponent<Rigidbody>().mass + JointParts[5].GetComponent<Rigidbody>().mass +
JointParts[6].GetComponent<Rigidbody>().mass + JointParts[7].GetComponent<Rigidbody>().mass +
JointParts[8].GetComponent<Rigidbody>().mass + JointParts[9].GetComponent<Rigidbody>().mass);
}
}
And here is my version of it (and below that you'll find my data class for the rig):
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ActiveRagdoll : MonoBehaviour
{
#region Inspector
[Header("Ragdoll Rig")]
[SerializeField] private RagdollRig rig;
[Header("Movement")]
[SerializeField] private float touchForce;
[SerializeField] private float timeStep;
[SerializeField] private float legHeight;
[SerializeField] private float fallFactor;
#endregion
#region Variables
private float _rightStepTime, _leftStepTime;
private bool _stepRight, _stepLeft, _walkForward, _walkBackwards, _falling;
private bool _flag, _flagRightLeg, _flagLeftLeg;
private Quaternion _startLegR1, _startLegR2, _startLegL1, _startLegL2;
private JointDrive _spring0, _spring150, _spring300, _spring320;
private Rigidbody _body;
#endregion
private void Awake()
{
_body = rig.torso.GetComponent<Rigidbody>();
Physics.IgnoreCollision(rig.rightArm.GetComponent<Collider>(),
rig.upperRightLeg.GetComponent<Collider>());
Physics.IgnoreCollision(rig.leftArm.GetComponent<Collider>(),
rig.upperLeftLeg.GetComponent<Collider>());
SetupSprings();
}
private void Update()
{
var input = Vector2.zero;
if (Input.GetKeyDown(KeyCode.UpArrow))
{
input = new Vector2(0, 1);
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
input = new Vector2(0, -1);
}
Movement(input);
}
public void Movement(Vector2 input)
{
if (input.y < -.3f)
_body.AddForce(Vector3.back * touchForce, ForceMode.Impulse);
else if (input.y > .3f)
_body.AddForce(Vector3.forward * touchForce, ForceMode.Impulse);
if (input.x < -.3f)
{
//TODO: ROTATE
}
else if (input.x > .3f)
{
//TODO: ROTATE
}
rig.centerOfMass.position = rig.CalculateCenterOfMass();
Balance();
if (!_walkForward && !_walkBackwards)
ResetMovement();
}
private void FixedUpdate()
{
MoveLegs();
}
private void Balance()
{
var comPosition = rig.centerOfMass.position;
var rightFootPosition = rig.rightFoot.transform.position;
var leftFootPosition = rig.leftFoot.transform.position;
if (comPosition.z < rightFootPosition.z && comPosition.z < leftFootPosition.z)
{
var targetRotation = rig.torso.targetRotation;
_walkBackwards = true;
rig.torso.targetRotation = Quaternion.Lerp(targetRotation, new Quaternion(-0.1f, targetRotation.y,
targetRotation.z, targetRotation.w), 6 * Time.fixedDeltaTime);
}
else
_walkBackwards = false;
if (comPosition.z > rightFootPosition.z && comPosition.z > leftFootPosition.z)
{
var targetRotation = rig.torso.targetRotation;
_walkForward = true;
rig.torso.targetRotation = Quaternion.Lerp(targetRotation,
new Quaternion(0, targetRotation.y, targetRotation.z, targetRotation.w), 6 * Time.fixedDeltaTime);
}
else
_walkForward = false;
_falling = comPosition.z > rightFootPosition.z + fallFactor && comPosition.z > leftFootPosition.z + fallFactor ||
comPosition.z < rightFootPosition.z - (fallFactor + 0.2f) && comPosition.z < leftFootPosition.z - (fallFactor + 0.2f);
if (_falling)
{
rig.pelvis.angularXDrive = _spring0;
rig.pelvis.angularYZDrive = _spring0;
legHeight = 5;
}
else
{
rig.pelvis.angularXDrive = _spring300;
rig.pelvis.angularYZDrive = _spring300;
legHeight = 1;
var rightArmRotation = rig.rightArm.targetRotation;
var leftArmRotation = rig.leftArm.targetRotation;
rig.rightArm.targetRotation = Quaternion.Lerp(rightArmRotation,
new Quaternion(0, rightArmRotation.y, rightArmRotation.z, rightArmRotation.w), 6 * Time.fixedDeltaTime);
rig.leftArm.targetRotation = Quaternion.Lerp(leftArmRotation,
new Quaternion(0, leftArmRotation.y, leftArmRotation.z, leftArmRotation.w), 6 * Time.fixedDeltaTime);
rig.rightArm.angularXDrive = _spring0;
rig.rightArm.angularYZDrive = _spring150;
rig.leftArm.angularXDrive = _spring0;
rig.leftArm.angularYZDrive = _spring150;
}
if (!(rig.torso.transform.position.y - 0.1f <= rig.pelvis.transform.position.y)) return;
rig.pelvis.angularXDrive = _spring0;
rig.pelvis.angularYZDrive = _spring0;
StandUp();
}
private void MoveLegs()
{
if (_walkForward)
{
if (rig.rightFoot.transform.position.z < rig.leftFoot.transform.position.z && !_stepLeft && !_flagRightLeg)
_stepRight = _flagRightLeg = _flagLeftLeg = true;
if (rig.rightFoot.transform.position.z > rig.leftFoot.transform.position.z && !_stepRight && !_flagLeftLeg)
_stepLeft = _flagLeftLeg = _flagRightLeg = true;
}
else if (_walkBackwards)
{
if (rig.rightFoot.transform.position.z > rig.leftFoot.transform.position.z && !_stepLeft && !_flagRightLeg)
_stepRight = _flagRightLeg = _flagLeftLeg = true;
if (rig.rightFoot.transform.position.z < rig.leftFoot.transform.position.z && !_stepRight && !_flagLeftLeg)
_stepLeft = _flagLeftLeg = _flagRightLeg = true;
}
TakeSteps();
}
private void TakeSteps()
{
if (_stepRight)
{
_rightStepTime += Time.fixedDeltaTime;
CalculateStep(ref rig.upperRightLeg, ref rig.lowerRightLeg, ref rig.upperLeftLeg);
if (_rightStepTime > timeStep)
{
_rightStepTime = 0;
_stepRight = false;
if (_walkBackwards || _walkForward)
_stepLeft = true;
}
}
else
LerpLegs(ref rig.upperRightLeg, ref rig.lowerRightLeg, _startLegR1, _startLegR2);
if (_stepLeft)
{
_leftStepTime += Time.fixedDeltaTime;
CalculateStep(ref rig.upperLeftLeg, ref rig.lowerLeftLeg, ref rig.upperRightLeg);
if (_leftStepTime > timeStep)
{
_leftStepTime = 0;
_stepLeft = false;
if (_walkBackwards || _walkForward)
_stepRight = true;
}
}
else
LerpLegs(ref rig.upperLeftLeg, ref rig.lowerLeftLeg, _startLegL1, _startLegL2);
}
private void StandUp()
{
rig.rightArm.angularXDrive = _spring320;
rig.rightArm.angularYZDrive = _spring320;
rig.leftArm.angularXDrive = _spring320;
rig.leftArm.angularYZDrive = _spring320;
if (_walkForward)
{
var targetRotation = rig.torso.targetRotation;
rig.torso.targetRotation = Quaternion.Lerp(targetRotation,
new Quaternion(-.1f, targetRotation.y, targetRotation.z,
targetRotation.w), 6 * Time.fixedDeltaTime);
RotateArmInDirection(ref rig.rightArm, 1.7f);
RotateArmInDirection(ref rig.leftArm, 1.7f);
}
if (!_walkBackwards) return;
RotateArmInDirection(ref rig.rightArm, -1.7f);
RotateArmInDirection(ref rig.leftArm, -1.7f);
}
private void ResetMovement()
{
_stepRight = _stepLeft = false;
_rightStepTime = _leftStepTime = 0;
_flagRightLeg = _flagLeftLeg = false;
var targetRotation = rig.torso.targetRotation;
rig.torso.targetRotation = Quaternion.Lerp(targetRotation,
new Quaternion(-.1f, targetRotation.y, targetRotation.z, targetRotation.w),
6 * Time.fixedDeltaTime);
}
private void SetupSprings()
{
_spring0 = new JointDrive
{
positionSpring = 0, positionDamper = 0,
maximumForce = Mathf.Infinity
};
_spring150 = new JointDrive
{
positionSpring = 150, positionDamper = 0,
maximumForce = Mathf.Infinity
};
_spring300 = new JointDrive
{
positionSpring = 300, positionDamper = 100,
maximumForce = Mathf.Infinity
};
_spring320 = new JointDrive
{
positionSpring = 320, positionDamper = 0,
maximumForce = Mathf.Infinity
};
}
private void RotateArmInDirection(ref ConfigurableJoint arm, float limit)
{
if (arm.targetRotation.x < limit)
{
var targetRotation = arm.targetRotation;
arm.targetRotation = new Quaternion(targetRotation.x + .07f, targetRotation.y,
targetRotation.z, targetRotation.w);
}
else if (arm.targetRotation.x < limit)
{
var targetRotation = arm.targetRotation;
arm.targetRotation = new Quaternion(targetRotation.x - .09f, targetRotation.y, targetRotation.z,
targetRotation.w);
}
}
private void LerpLegs(ref ConfigurableJoint upperLeg, ref ConfigurableJoint lowerLeg, Quaternion upperStart, Quaternion lowerStart)
{
upperLeg.targetRotation =
Quaternion.Lerp(upperLeg.targetRotation, upperStart, 8f * Time.fixedDeltaTime);
lowerLeg.targetRotation =
Quaternion.Lerp(lowerLeg.targetRotation, lowerStart, 17f * Time.fixedDeltaTime);
}
private void CalculateStep(ref ConfigurableJoint upperDominant, ref ConfigurableJoint lowerDominant,
ref ConfigurableJoint upperSupport)
{
var upperDominantRotation = upperDominant.targetRotation;
var lowerDominantRotation = lowerDominant.targetRotation;
var upperSupportRotation = upperSupport.targetRotation;
if (_walkForward)
{
upperDominant.targetRotation = new Quaternion(upperDominantRotation.x + 0.07f * legHeight, upperDominantRotation.y,
upperDominantRotation.z, upperDominantRotation.w);
lowerDominant.targetRotation = new Quaternion(lowerDominantRotation.x - 0.04f * legHeight * 2,
lowerDominantRotation.y, lowerDominantRotation.z, lowerDominantRotation.w);
upperSupport.targetRotation = new Quaternion(upperSupportRotation.x - 0.02f * legHeight / 2,
upperSupportRotation.y, upperSupportRotation.z, upperSupportRotation.w);
}
if (!_walkBackwards) return;
upperDominant.targetRotation = new Quaternion(upperDominantRotation.x - 0.00f * legHeight, upperDominantRotation.y,
upperDominantRotation.z, upperDominantRotation.w);
lowerDominant.targetRotation = new Quaternion(lowerDominantRotation.x - 0.06f * legHeight * 2,
lowerDominantRotation.y, lowerDominantRotation.z, lowerDominantRotation.w);
upperSupport.targetRotation = new Quaternion(upperSupportRotation.x + 0.02f * legHeight / 2,
upperSupportRotation.y, upperSupportRotation.z, upperSupportRotation.w);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class RagdollRig
{
public ConfigurableJoint torso,
pelvis,
rightArm,
leftArm,
upperRightLeg,
lowerRightLeg,
rightFoot,
upperLeftLeg,
lowerLeftLeg,
leftFoot;
public Transform centerOfMass;
private List<Rigidbody> GetRigidbodies()
{
return new List<Rigidbody>
{
torso.gameObject.GetComponent<Rigidbody>(),
pelvis.gameObject.GetComponent<Rigidbody>(),
rightArm.gameObject.GetComponent<Rigidbody>(),
leftArm.gameObject.GetComponent<Rigidbody>(),
upperRightLeg.gameObject.GetComponent<Rigidbody>(),
lowerRightLeg.gameObject.GetComponent<Rigidbody>(),
rightFoot.gameObject.GetComponent<Rigidbody>(),
upperLeftLeg.gameObject.GetComponent<Rigidbody>(),
lowerLeftLeg.gameObject.GetComponent<Rigidbody>(),
leftFoot.gameObject.GetComponent<Rigidbody>()
};
}
public Vector3 CalculateCenterOfMass()
{
var parts = GetRigidbodies();
var mass = Vector3.zero;
float division = 0;
foreach (var t in parts)
{
var objMass = t.mass;
mass += objMass * t.transform.position;
division += objMass;
}
return mass / division;
}
}
Just to make it a bit easier for you to check out here is a dropbox link to the Unity project itself.
Any tips or ideas on how to fix this is really appreciated!
Alright, so I ended up just deleting my refactored code above (except the ragdoll rig class) and start over.
I'm not a 100% certain as to why it didn't work before but I think I might have swapped some variables a couple of places.
Some of the functions that I created in the previous script might also have been the culprit so I decided to not go with the ref functions that I created.
Anyways, this is what I ended up with, hope it's useful to anyone who might want to toy around with active ragdolls
``
using UnityEngine;
using Quaternion = UnityEngine.Quaternion;
using Vector2 = UnityEngine.Vector2;
using Vector3 = UnityEngine.Vector3;
public class ActiveRagdoll : MonoBehaviour
{
#region Inspector
[Header("Ragdoll Rig")] [SerializeField]
private RagdollRig rig;
[Header("Movement")] [SerializeField] private float touchForce;
[SerializeField] private float timeStep;
[SerializeField] private float legHeight;
[SerializeField] private float fallFactor;
#endregion
#region Variables
private float _rightStepTime, _leftStepTime;
private bool _stepRight, _stepLeft, _walkForward, _walkBackwards, _falling;
private bool _flag, _flagRightLeg, _flagLeftLeg;
private Quaternion _startLegR1, _startLegR2, _startLegL1, _startLegL2;
private JointDrive _spring0, _spring150, _spring300, _spring320;
private Rigidbody _body;
#endregion
private void Awake()
{
rig.InitializeRig();
_body = rig.torso.gameObject.GetComponent<Rigidbody>();
Physics.IgnoreCollision(rig.rightArm.GetComponent<Collider>(), rig.upperRightLeg.GetComponent<Collider>(),
true);
Physics.IgnoreCollision(rig.leftArm.GetComponent<Collider>(), rig.upperLeftLeg.GetComponent<Collider>(), true);
SetupJoints();
}
//FOR TESTING, REMOVE LATER
private void Update()
{
MovementInput(new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")));
}
private void FixedUpdate()
{
LegsMoving();
}
public void MovementInput(Vector2 input)
{
var direction = new Vector3(input.x, 0, input.y);
if (input.y < 0 || input.y > 0)
_body.AddForce(Time.fixedDeltaTime * touchForce * direction, ForceMode.Impulse);
rig.centerOfMass.position = rig.CalculateCenterOfMass();
Balance();
if (!_walkForward && !_walkBackwards)
ResetMovement();
}
private void ResetMovement()
{
var targetRotation = rig.torso.targetRotation;
_stepRight = false;
_stepLeft = false;
_rightStepTime = 0;
_leftStepTime = 0;
_flagRightLeg = false;
_flagLeftLeg = false;
rig.torso.targetRotation = Quaternion.Lerp(targetRotation,
new Quaternion(-0.1f, targetRotation.y, targetRotation.z, targetRotation.w), 6 * Time.fixedDeltaTime);
}
private void Balance()
{
var comPosition = rig.centerOfMass.transform.position;
var rightFootPosition = rig.rightFoot.transform.position;
var leftFootPosition = rig.leftFoot.transform.position;
var targetRotation = rig.torso.targetRotation;
_walkBackwards = comPosition.z < rightFootPosition.z && comPosition.z < leftFootPosition.z;
if (_walkBackwards)
rig.torso.targetRotation = Quaternion.Lerp(targetRotation,
new Quaternion(-0.1f, targetRotation.y, targetRotation.z, targetRotation.w), 6 * Time.fixedDeltaTime);
_walkForward = comPosition.z > rightFootPosition.z && comPosition.z > leftFootPosition.z;
if (_walkForward)
rig.torso.targetRotation = Quaternion.Lerp(targetRotation,
new Quaternion(0, targetRotation.y, targetRotation.z, targetRotation.w), 6 * Time.fixedDeltaTime);
CheckForFall(comPosition, rightFootPosition, leftFootPosition);
if (!(rig.torso.transform.position.y - 0.1f <= rig.pelvis.transform.position.y)) return;
rig.pelvis.angularXDrive = _spring0;
rig.pelvis.angularYZDrive = _spring0;
StandUp();
}
private void LegsMoving()
{
var upperRightLegRotation = rig.upperRightLeg.targetRotation;
var lowerRightLegRotation = rig.lowerRightLeg.targetRotation;
var upperLeftLegRotation = rig.upperLeftLeg.targetRotation;
var lowerLeftLegRotation = rig.lowerLeftLeg.targetRotation;
CheckFooting(rig.rightFoot.transform.position, rig.leftFoot.transform.position);
if (_stepRight)
{
_rightStepTime += Time.fixedDeltaTime;
if (_walkForward)
{
rig.upperRightLeg.targetRotation = new Quaternion(upperRightLegRotation.x + 0.07f * legHeight, upperRightLegRotation.y,
upperRightLegRotation.z, upperRightLegRotation.w);
rig.lowerRightLeg.targetRotation = new Quaternion(lowerRightLegRotation.x - 0.04f * legHeight * 2, lowerRightLegRotation.y,
lowerRightLegRotation.z, lowerRightLegRotation.w);
rig.upperLeftLeg.targetRotation = new Quaternion(upperLeftLegRotation.x - 0.02f * legHeight / 2, upperLeftLegRotation.y,
upperLeftLegRotation.z, upperLeftLegRotation.w);
}
if (_walkBackwards)
{
rig.upperRightLeg.targetRotation = new Quaternion(upperRightLegRotation.x - 0.00f * legHeight, upperRightLegRotation.y,
upperRightLegRotation.z, upperRightLegRotation.w);
rig.lowerRightLeg.targetRotation = new Quaternion(lowerRightLegRotation.x - 0.06f * legHeight * 2, lowerRightLegRotation.y,
lowerRightLegRotation.z, lowerRightLegRotation.w);
rig.upperLeftLeg.targetRotation = new Quaternion(upperLeftLegRotation.x + 0.02f * legHeight / 2, upperLeftLegRotation.y,
upperLeftLegRotation.z, upperLeftLegRotation.w);
}
if (_rightStepTime > timeStep)
{
_rightStepTime = 0;
_stepRight = false;
_stepLeft = _walkBackwards || _walkForward;
}
}
else
{
rig.upperRightLeg.targetRotation = Quaternion.Lerp(upperRightLegRotation, _startLegR1,
8f * Time.fixedDeltaTime);
rig.lowerRightLeg.targetRotation = Quaternion.Lerp(lowerRightLegRotation, _startLegR2,
17f * Time.fixedDeltaTime);
}
if (_stepLeft)
{
_leftStepTime += Time.fixedDeltaTime;
if (_walkForward)
{
rig.upperLeftLeg.targetRotation = new Quaternion(upperLeftLegRotation.x + 0.07f * legHeight, upperLeftLegRotation.y,
upperLeftLegRotation.z, upperLeftLegRotation.w);
rig.lowerLeftLeg.targetRotation = new Quaternion(lowerLeftLegRotation.x - 0.04f * legHeight * 2, lowerLeftLegRotation.y,
lowerLeftLegRotation.z, lowerLeftLegRotation.w);
rig.upperRightLeg.targetRotation = new Quaternion(upperRightLegRotation.x - 0.02f * legHeight / 2, upperRightLegRotation.y,
upperRightLegRotation.z, upperRightLegRotation.w);
}
if (_walkBackwards)
{
rig.upperLeftLeg.targetRotation = new Quaternion(upperLeftLegRotation.x - 0.00f * legHeight,
upperLeftLegRotation.y, upperLeftLegRotation.z, upperLeftLegRotation.w);
rig.lowerLeftLeg.targetRotation = new Quaternion(lowerLeftLegRotation.x - 0.06f * legHeight * 2,
lowerLeftLegRotation.y, lowerLeftLegRotation.z, lowerLeftLegRotation.w);
rig.upperRightLeg.targetRotation = new Quaternion(upperRightLegRotation.x + 0.02f * legHeight / 2,
upperRightLegRotation.y, upperRightLegRotation.z, upperRightLegRotation.w);
}
if (_leftStepTime > timeStep)
{
_leftStepTime = 0;
_stepLeft = false;
_stepRight = _walkBackwards || _walkForward;
}
}
else
{
rig.upperLeftLeg.targetRotation = Quaternion.Lerp(upperLeftLegRotation, _startLegL1, (8) * Time.fixedDeltaTime);
rig.lowerLeftLeg.targetRotation = Quaternion.Lerp(lowerLeftLegRotation, _startLegL2, (17) * Time.fixedDeltaTime);
}
}
private void CheckFooting(Vector3 rightFoot, Vector3 leftFoot)
{
if (_walkForward)
{
if (rightFoot.z < leftFoot.z && !_stepLeft && !_flagRightLeg)
_stepRight = _flagRightLeg = _flagLeftLeg = true;
if (rightFoot.z > leftFoot.z && !_stepRight && !_flagLeftLeg)
_stepLeft = _flagLeftLeg = _flagRightLeg = true;
}
if (!_walkBackwards) return;
if (rightFoot.z > leftFoot.z && !_stepLeft && !_flagRightLeg)
_stepRight = _flagRightLeg = _flagLeftLeg = true;
if (rightFoot.z < leftFoot.z && !_stepRight && !_flagLeftLeg)
_stepLeft = _flagLeftLeg = _flagRightLeg = true;
}
private void StandUp()
{
var leftArmRotation = rig.leftArm.targetRotation;
var rightArmRotation = rig.rightArm.targetRotation;
var torsoRotation = rig.torso.targetRotation;
rig.rightArm.angularXDrive = _spring320;
rig.rightArm.angularYZDrive = _spring320;
rig.leftArm.angularXDrive = _spring320;
rig.leftArm.angularYZDrive = _spring320;
if (_walkForward)
{
rig.torso.targetRotation = Quaternion.Lerp(torsoRotation, new Quaternion(-0.1f,
torsoRotation.y,torsoRotation.z, torsoRotation.w), 6 * Time.fixedDeltaTime);
if (rightArmRotation.x < 1.7f)
rig.rightArm.targetRotation = new Quaternion(rightArmRotation.x + 0.07f,
rightArmRotation.y,rightArmRotation.z, rightArmRotation.w);
if (leftArmRotation.x < 1.7f)
rig.leftArm.targetRotation = new Quaternion(leftArmRotation.x + 0.07f,
leftArmRotation.y,leftArmRotation.z, leftArmRotation.w);
}
if (_walkBackwards)
{
if (rightArmRotation.x > -1.7f)
rig.rightArm.targetRotation = new Quaternion(rightArmRotation.x - 0.09f,
rightArmRotation.y,rightArmRotation.z, rightArmRotation.w);
if (leftArmRotation.x > -1.7f)
rig.leftArm.targetRotation = new Quaternion(leftArmRotation.x - 0.09f,
leftArmRotation.y,leftArmRotation.z, leftArmRotation.w);
}
}
private void CheckForFall(Vector3 comPosition, Vector3 rightFootPosition, Vector3 leftFootPosition)
{
_falling = comPosition.z > rightFootPosition.z + fallFactor && comPosition.z > leftFootPosition.z + fallFactor ||
comPosition.z < rightFootPosition.z - (fallFactor + 0.2f) && comPosition.z < leftFootPosition.z - (fallFactor + 0.2f);
if (_falling)
{
rig.pelvis.angularXDrive = _spring0;
rig.pelvis.angularYZDrive = _spring0;
legHeight = 5;
}
else
{
var rightArmRotation = rig.rightArm.targetRotation;
var leftArmRotation = rig.leftArm.targetRotation;
rig.pelvis.angularXDrive = _spring300;
rig.pelvis.angularYZDrive = _spring300;
legHeight = 1;
rig.rightArm.targetRotation = Quaternion.Lerp(rightArmRotation,
new Quaternion(0, rightArmRotation.y, rightArmRotation.z, rightArmRotation.w), 6 * Time.fixedDeltaTime);
rig.leftArm.targetRotation = Quaternion.Lerp(leftArmRotation,
new Quaternion(0, leftArmRotation.y, leftArmRotation.z, leftArmRotation.w), 6 * Time.fixedDeltaTime);
rig.rightArm.angularXDrive = _spring0;
rig.rightArm.angularYZDrive = _spring150;
rig.leftArm.angularXDrive = _spring0;
rig.leftArm.angularYZDrive = _spring150;
}
}
private void SetupJoints()
{
_startLegR1 = rig.upperRightLeg.targetRotation;
_startLegR2 = rig.lowerRightLeg.targetRotation;
_startLegL1 = rig.upperLeftLeg.targetRotation;
_startLegL2 = rig.lowerLeftLeg.targetRotation;
_spring0 = new JointDrive {positionSpring = 0, positionDamper = 0, maximumForce = Mathf.Infinity};
_spring150 = new JointDrive {positionSpring = 150, positionDamper = 0, maximumForce = Mathf.Infinity};
_spring300 = new JointDrive {positionSpring = 300, positionDamper = 100, maximumForce = Mathf.Infinity};
_spring320 = new JointDrive {positionSpring = 320, positionDamper = 0, maximumForce = Mathf.Infinity};
}
}
``
and then the rig class
``
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class RagdollRig
{
public ConfigurableJoint torso,
pelvis,
rightArm,
leftArm,
upperRightLeg,
lowerRightLeg,
rightFoot,
upperLeftLeg,
lowerLeftLeg,
leftFoot;
public Transform centerOfMass;
private List<Rigidbody> _rigidbodies;
public void InitializeRig()
{
_rigidbodies = GetRigidbodies();
}
private List<Rigidbody> GetRigidbodies()
{
return new List<Rigidbody>
{
torso.gameObject.GetComponent<Rigidbody>(),
pelvis.gameObject.GetComponent<Rigidbody>(),
rightArm.gameObject.GetComponent<Rigidbody>(),
leftArm.gameObject.GetComponent<Rigidbody>(),
upperRightLeg.gameObject.GetComponent<Rigidbody>(),
lowerRightLeg.gameObject.GetComponent<Rigidbody>(),
rightFoot.gameObject.GetComponent<Rigidbody>(),
upperLeftLeg.gameObject.GetComponent<Rigidbody>(),
lowerLeftLeg.gameObject.GetComponent<Rigidbody>(),
leftFoot.gameObject.GetComponent<Rigidbody>()
};
}
public Vector3 CalculateCenterOfMass()
{
var mass = Vector3.zero;
float division = 0;
foreach (var t in _rigidbodies)
{
var objMass = t.mass;
mass += objMass * t.transform.position;
division += objMass;
}
return mass / division;
}
}
``
Again, huge thank you to MetalCore999 (Youtube) for publishing his original script.

My highscore doesn't match my points at sometimes

When I get my points(poang) to highscore when I hit the blocks with 5 points. They will not update the same, sometimes points(poang) will be 18 and highscore will be 20.
(Sorry about my bad english)
poang = points
linje = line
liv = lives
boll = ball
poang = points
blockröd = blockred
blockgrön = blockgreen
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont spritefont;
Texture2D linje_texture;
Texture2D linjeliten_texture;
Texture2D boll_texture;
Texture2D blockröd_texture;
Texture2D blockgrön_texture;
Texture2D gameover_texture;
Rectangle linje_rect;
Rectangle linjeliten_rect;
Rectangle boll_rect;
Rectangle blockröd_rect;
Rectangle blockgrön_rect;
Rectangle gameover_rect;
Vector2 linje_speed;
Vector2 linjeliten_speed;
Vector2 boll_speed;
Random random;
StreamReader sr;
StreamWriter sw;
int liv = 3;
int poang = 0;
int highscore;
List<Rectangle> block = new List<Rectangle>();
List<Rectangle> block2 = new List<Rectangle>();
bool Start = false;
bool holdingleft = false;
bool holdingright = false;
bool resetballspeed = false;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferWidth = 760;
graphics.PreferredBackBufferHeight = 620;
}
protected override void Initialize()
{
random = new Random();
linje_speed.X = 6f;
linjeliten_speed.X = 6f;
boll_speed.X = random.Next(-1, 1);
boll_speed.Y = 7f;
sr = new StreamReader("highscore.txt");
highscore = int.Parse(sr.ReadLine());
sr.Close();
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
spritefont = Content.Load<SpriteFont>("Fonts/Myfont");
linje_texture = Content.Load<Texture2D>("Pics/linje-lång");
linjeliten_texture = Content.Load<Texture2D>("Pics/linje");
boll_texture = Content.Load<Texture2D>("Pics/boll");
blockgrön_texture = Content.Load<Texture2D>("Pics/block-grön");
blockröd_texture = Content.Load<Texture2D>("Pics/block-röd");
gameover_texture = Content.Load<Texture2D>("Pics/GameOver");
linje_rect = new Rectangle((Window.ClientBounds.Width - linje_texture.Width) / 2, 580, linje_texture.Width, linje_texture.Height);
linjeliten_rect = new Rectangle((Window.ClientBounds.Width - linjeliten_texture.Width) / 2, 580, linjeliten_texture.Width, linjeliten_texture.Height);
boll_rect = new Rectangle((Window.ClientBounds.Width - boll_texture.Width) / 2, 556, boll_texture.Width, boll_texture.Height);
gameover_rect = new Rectangle((Window.ClientBounds.Width / 2) - (gameover_texture.Width / 2), (Window.ClientBounds.Height / 2) - gameover_texture.Height / 2, gameover_texture.Width, gameover_texture.Height);
block.Add(blockgrön_rect);
block2.Add(blockröd_rect);
for (int i = 1; i < 2; i++)
{
for (int g = 1; g < 13; g++)
{
block2.Add(new Rectangle((g * 63) - 60, (i * 20), blockröd_texture.Width, blockröd_texture.Height));
}
}
for (int i = 1; i < 4; i++)
{
for (int g = 1; g < 13; g++)
{
block.Add(new Rectangle((g * 63) - 60, (i * 20) + 20, blockgrön_texture.Width, blockgrön_texture.Height));
}
}
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
{
if (poang == highscore)
{
sw = new StreamWriter("highscore.txt");
sw.WriteLine(poang);
sw.Close();
}
Exit();
}
if (Start == true)
{
boll_rect.X += (int)boll_speed.X;
boll_rect.Y += (int)boll_speed.Y;
}
if (Start == false)
{
boll_rect.X = linje_rect.X + ((linje_texture.Width / 2) - (boll_texture.Width / 2)); //how the ball condition is to the long line
boll_rect.X = linjeliten_rect.X + ((linjeliten_texture.Width / 2) - (boll_texture.Width / 2)); //the same but ball condition to small line
}
if (boll_rect.X > Window.ClientBounds.Width - boll_texture.Width || boll_rect.X < 0)
boll_speed.X *= -1;
if (boll_rect.Y > Window.ClientBounds.Height - boll_texture.Height || boll_rect.Y < 0)
boll_speed.Y *= -1;
if (boll_rect.Y > Window.ClientBounds.Height - boll_texture.Height)
{
liv -= 1;
Start = false;
boll_rect.X = (Window.ClientBounds.Width - boll_texture.Width) / 2;
boll_rect.Y = 556;
linje_rect.X = (Window.ClientBounds.Width - linje_texture.Width) / 2;
linje_rect.Y = 580;
linjeliten_rect.X = (Window.ClientBounds.Width - linjeliten_texture.Width) / 2;
linjeliten_rect.Y = 580;
}
KeyboardState ks = Keyboard.GetState();
if (ks.IsKeyDown(Keys.Left))
{
linje_rect.X -= (int)linje_speed.X;
linjeliten_rect.X -= (int)linjeliten_speed.X;
holdingleft = true;
}
else if (ks.IsKeyDown(Keys.Right))
{
linje_rect.X += (int)linje_speed.X;
linjeliten_rect.X += (int)linjeliten_speed.X;
holdingright = true;
}
else if (ks.IsKeyDown(Keys.Space))
{
Start = true;
}
if (ks.Equals(new KeyboardState()))
{
resetballspeed = true;
}
if (linje_rect.X > Window.ClientBounds.Width - linje_texture.Width)
linje_rect.X = (Window.ClientBounds.Width - linje_texture.Width);
if (linjeliten_rect.X > Window.ClientBounds.Width - linjeliten_texture.Width)
linjeliten_rect.X = (Window.ClientBounds.Width - linjeliten_texture.Width);
if (linje_rect.X < 0)
linje_rect.X = 0;
if (linjeliten_rect.X < 0)
linjeliten_rect.X = 0;
if (linje_rect.Intersects(boll_rect))
{
boll_speed.Y *= -1;
boll_rect.Y += (int)boll_speed.Y;
if (holdingleft == true)
{
boll_speed.X -= 2;
}
else if (holdingright == true)
{
boll_speed.X += 2;
}
else if (resetballspeed == true)
{
boll_speed.X = 1;
}
}
if (linjeliten_rect.Intersects(boll_rect))
{
boll_speed.Y *= -1;
boll_rect.Y += (int)boll_speed.Y;
if (holdingleft == true)
{
boll_speed.X -= 1;
}
else if (holdingright == true)
{
boll_speed.X += 1;
}
else if (resetballspeed == true)
{
boll_speed.X = 1;
}
}
for (int j = 1; j < block.Count; j++)
{
if (boll_rect.Intersects(block[j]))
{
boll_speed.Y *= -1;
poang += 1;
block.RemoveAt(j);
if (poang > highscore)
{
highscore++;
}
}
}
for (int k = 1; k < block2.Count; k++)
{
if (boll_rect.Intersects(block2[k]))
{
boll_speed.Y *= -1;
poang += 5;
block2.RemoveAt(k);
if (poang > highscore)
{
highscore += 5;
}
}
}
holdingleft = false;
holdingright = false;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
if (liv > 0)
{
if (poang < 10)
{
spriteBatch.Draw(linje_texture, linje_rect, Color.White);
}
else if (poang > 9)
{
spriteBatch.Draw(linjeliten_texture, linjeliten_rect, Color.White);
}
spriteBatch.Draw(boll_texture, boll_rect, Color.White);
spriteBatch.DrawString(spritefont, "Lives left: " + liv, Vector2.Zero, Color.White);
spriteBatch.DrawString(spritefont, "Points: " + poang, new Vector2(350, 0), Color.White);
spriteBatch.DrawString(spritefont, "Highscore: " + highscore, new Vector2(660, 0), Color.White);
foreach (Rectangle g in block)
{
spriteBatch.Draw(blockgrön_texture, g, Color.White);
}
foreach (Rectangle t in block2)
{
spriteBatch.Draw(blockröd_texture, t, Color.White);
}
}
else if (liv == 0)
{
spriteBatch.Draw(gameover_texture, gameover_rect, Color.White);
if (poang == highscore)
{
sw = new StreamWriter("highscore.txt");
sw.WriteLine(poang);
sw.Close();
}
}
spriteBatch.End();
base.Draw(gameTime);
}
}
Having trouble with these parts:
for (int j = 1; j < block.Count; j++) //loopar igenom alla block
{
if (boll_rect.Intersects(block[j])) //om bollen träffar rutorna
{
boll_speed.Y *= -1;
poang += 1;
block.RemoveAt(j); //tar bort gröna blocket man träffar
if (poang > 9)
{
linje_rect.Width = 60;
}
if (poang > highscore)
{
highscore++;
}
}
}
for (int k = 1; k < block2.Count; k++)
{
if (boll_rect.Intersects(block2[k]))
{
boll_speed.Y *= -1;
poang += 5;
block2.RemoveAt(k);
if (poang > highscore)
{
highscore += 5;
}
block2.RemoveAt(k);
}
}
Replace highscore++; with highscore = poang;
and highscore += 5; with highscore = poang;
to avoid mismatches between highscore and current score.

Trying to add new levels to my Breakout game

I have a problem with my code, check the code down below, so you understand which section i'm talking about!
I'm trying to add new block levels when "block.Count == 1", you know when all my blocks are destroyed by the ball. I want it to start a new level with a different block path. When I have:
else if (block.Count == 1 && block2.Count == 1)
{
spriteBatch.Draw(gameover_texture, gameover_rect, Color.White);
}
It doesn't draw out my gameover_texture, when are blocks are gone?
(Sorry about my bad english)
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont spritefont;
Texture2D paddle_texture;
Texture2D ball_texture;
Texture2D blockred_texture;
Texture2D blockgreen_texture;
Texture2D gameover_texture;
Rectangle paddle_rect;
Rectangle ball_rect;
Rectangle blockred_rect;
Rectangle blockgreen_rect;
Rectangle gameover_rect;
Vector2 paddle_speed;
Vector2 ball_speed;
Random random;
StreamReader sr;
StreamWriter sw;
int lives = 3;
int points = 0;
int highscore;
int counter = 0;
int seconds = 0;
List<Rectangle> block = new List<Rectangle>();
List<Rectangle> block2 = new List<Rectangle>();
bool Start = false;
bool holdingleft = false;
bool holdingright = false;
bool resetballspeed = false;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferWidth = 760;
graphics.PreferredBackBufferHeight = 620;
}
protected override void Initialize()
{
random = new Random();
paddle_speed.X = 6f;
ball_speed.X = random.Next(-1, 1);
ball_speed.Y = 7f;
sr = new StreamReader("highscore.txt");
highscore = int.Parse(sr.ReadLine());
sr.Close();
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
spritefont = Content.Load<SpriteFont>("Fonts/Myfont");
paddle_texture = Content.Load<Texture2D>("Pics/linje");
ball_texture = Content.Load<Texture2D>("Pics/boll");
blockgreen_texture = Content.Load<Texture2D>("Pics/block-grön");
blockred_texture = Content.Load<Texture2D>("Pics/block-röd");
gameover_texture = Content.Load<Texture2D>("Pics/GameOver");
paddle_rect = new Rectangle((Window.ClientBounds.Width - paddle_texture.Width) / 2, 580, paddle_texture.Width, paddle_texture.Height);
ball_rect = new Rectangle((Window.ClientBounds.Width - ball_texture.Width) / 2, 556, ball_texture.Width, ball_texture.Height);
gameover_rect = new Rectangle((Window.ClientBounds.Width / 2) - (gameover_texture.Width / 2), (Window.ClientBounds.Height / 2) - gameover_texture.Height / 2, gameover_texture.Width, gameover_texture.Height);
block.Add(blockgreen_rect);
block2.Add(blockred_rect);
for (int i = 1; i < 2; i++)
{
for (int g = 1; g < 3; g++)
{
block2.Add(new Rectangle((g * 63) - 60, (i * 40), blockred_texture.Width, blockred_texture.Height));
}
}
for (int i = 1; i < 2; i++)
{
for (int g = 1; g < 3; g++)
{
block.Add(new Rectangle((g * 63) - 60, (i * 20) + 40, blockgreen_texture.Width, blockgreen_texture.Height));
}
}
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
if (Start == true) //kolla om "Start == true",
{
ball_rect.X += (int)ball_speed.X;
ball_rect.Y += (int)ball_speed.Y;
}
if (Start == false)
{
ball_rect.X = paddle_rect.X + ((paddle_rect.Width / 2) - (ball_texture.Width / 2));
}
if (ball_rect.X > Window.ClientBounds.Width - ball_texture.Width || ball_rect.X < 0)
ball_speed.X *= -1;
if (ball_rect.Y > Window.ClientBounds.Height - ball_texture.Height || ball_rect.Y < 0)
ball_speed.Y *= -1;
if (ball_rect.Y > Window.ClientBounds.Height - ball_texture.Height)
{
lives -= 1;
Start = false;
ball_rect.X = (Window.ClientBounds.Width - ball_texture.Width) / 2;
ball_rect.Y = 556;
paddle_rect.X = (Window.ClientBounds.Width - paddle_texture.Width) / 2;
paddle_rect.Y = 580;
}
KeyboardState ks = Keyboard.GetState();
if (ks.IsKeyDown(Keys.Left))
{
paddle_rect.X -= (int)paddle_speed.X;
holdingleft = true;
}
else if (ks.IsKeyDown(Keys.Right))
{
paddle_rect.X += (int)paddle_speed.X;
holdingright = true;
}
else if (ks.IsKeyDown(Keys.Space))
{
Start = true;
}
else if (ks.Equals(new KeyboardState()))
{
resetballspeed = true;
}
if (paddle_rect.X > Window.ClientBounds.Width - paddle_rect.Width)
paddle_rect.X = (Window.ClientBounds.Width - paddle_rect.Width);
if (paddle_rect.X < 0)
paddle_rect.X = 0;
if (paddle_rect.Intersects(ball_rect))
{
ball_speed.Y *= -1;
ball_rect.Y += (int)ball_speed.Y;
if (holdingleft == true)
{
ball_speed.X -= 3;
}
else if (holdingright == true)
{
ball_speed.X += 3;
}
else if (resetballspeed == true)
{
ball_speed.X = 1;
}
}
if (points == highscore)
{
sw = new StreamWriter("highscore.txt");
sw.WriteLine(points);
sw.Close();
}
for (int j = 1; j < block.Count; j++)
{
if (ball_rect.Intersects(block[j]))
{
ball_speed.Y *= -1;
points += 1;
block.RemoveAt(j);
if (points > 9)
{
paddle_rect.Width = 60;
}
if (points > highscore)
{
highscore = points;
}
}
}
for (int k = 1; k < block2.Count; k++)
{
if (ball_rect.Intersects(block2[k]))
{
ball_speed.Y *= -1;
points += 5;
block2.RemoveAt(k);
if (points > 9)
{
paddle_rect.Width = 60;
}
if (points > highscore)
{
highscore = points;
}
}
}
holdingleft = false;
holdingright = false;
counter++;
if (counter == 60)
{
seconds++;
counter = 0;
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
// TODO: Add your drawing code here
spriteBatch.Begin();
if (lives > 0)
{
spriteBatch.Draw(ball_texture, ball_rect, Color.White);
spriteBatch.Draw(paddle_texture, paddle_rect, Color.White);
spriteBatch.DrawString(spritefont, "Lives left: " + lives, Vector2.Zero, Color.White);
spriteBatch.DrawString(spritefont, "Points: " + points, new Vector2(350, 0), Color.White);
spriteBatch.DrawString(spritefont, "Timer: " + seconds, new Vector2(350, 600), Color.White);
spriteBatch.DrawString(spritefont, "Highscore: " + highscore, new Vector2(660, 0), Color.White);
foreach (Rectangle g in block)
{
spriteBatch.Draw(blockgreen_texture, g, Color.White);
}
foreach (Rectangle t in block2)
{
spriteBatch.Draw(blockred_texture, t, Color.White);
}
}
else if (block.Count == 1 && block2.Count == 1)
{
spriteBatch.Draw(gameover_texture, gameover_rect, Color.White);
}
else if (lives == 0)
{
spriteBatch.Draw(gameover_texture, gameover_rect, Color.White);
}
spriteBatch.End();
base.Draw(gameTime);
}
}
Fixed the problem now, by putting the else if-statement inside "if (lives > 0)"

Is there a way to find progress completion of ObjImporter drawing mesh in Unity C#?

In my Unity project, I want to have a progress bar that starts loading when I import a .obj model during runtime.
How I want to it work is when I press "spacebar", the ObjImporter would start importing/drawing the assigned model and during that period of time while it's drawing, there would be a progress bar somewhere that shows the completion of the importing+/drawing progress, so the user could see the estimated amount of time neededto complete and not get impatient.
I'm using a slightly modified ObjImporter.cs from unity wiki:
/* This version of ObjImporter first reads through the entire file, getting a count of how large
* the final arrays will be, and then uses standard arrays for everything (as opposed to ArrayLists
* or any other fancy things).
*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
public class ObjImporter : MonoBehaviour {
public GameObject spawnPoint;
public GameObject emptyPrefabWithMeshRenderer;
public string meshPath;
public GameObject spawnedPrefab;
public float progressPercentage;
int noOfLines;
void Start ()
{
progressPercentage = 0;
}
void Update ()
{
if(Input.GetKeyDown("space")){
Mesh importedMesh = GetComponent<ObjImporter>().ImportFile(meshPath);
noOfLines = TotalLines(meshPath);
spawnedPrefab=Instantiate(emptyPrefabWithMeshRenderer,spawnPoint.transform.position,spawnPoint.transform.rotation) as GameObject;
spawnedPrefab.GetComponent<MeshFilter>().mesh=importedMesh;
spawnedPrefab.GetComponent<Renderer>().material.color = new Color(Random.value, Random.value, Random.value, 1.0f);
}
}
private struct meshStruct
{
public Vector3[] vertices;
public Vector3[] normals;
public Vector2[] uv;
public Vector2[] uv1;
public Vector2[] uv2;
public int[] triangles;
public int[] faceVerts;
public int[] faceUVs;
public Vector3[] faceData;
public string name;
public string fileName;
}
// Use this for initialization
public Mesh ImportFile (string filePath){
meshStruct newMesh = createMeshStruct(filePath);
populateMeshStruct(ref newMesh);
Vector3[] newVerts = new Vector3[newMesh.faceData.Length];
Vector2[] newUVs = new Vector2[newMesh.faceData.Length];
Vector3[] newNormals = new Vector3[newMesh.faceData.Length];
int i = 0;
/* The following foreach loops through the facedata and assigns the appropriate vertex, uv, or normal
* for the appropriate Unity mesh array.
*/
foreach (Vector3 v in newMesh.faceData)
{
newVerts[i] = newMesh.vertices[(int)v.x - 1];
if (v.y >= 1)
newUVs[i] = newMesh.uv[(int)v.y - 1];
if (v.z >= 1)
newNormals[i] = newMesh.normals[(int)v.z - 1];
i++;
}
Mesh mesh = new Mesh();
mesh.vertices = newVerts;
mesh.uv = newUVs;
mesh.normals = newNormals;
mesh.triangles = newMesh.triangles;
mesh.RecalculateBounds();
mesh.Optimize ();
return mesh;
}
private int TotalLines(string filePath)
{
using (StreamReader r = new StreamReader(filePath))
{
int i = 0;
while (r.ReadLine() != null)
{
i++;
}
return i;
}
}
private static meshStruct createMeshStruct(string filename)
{
int triangles = 0;
int vertices = 0;
int vt = 0;
int vn = 0;
int face = 0;
meshStruct mesh = new meshStruct();
mesh.fileName = filename;
// Read and retrieve all the text in the file.
StreamReader stream = File.OpenText(filename);
string entireText = stream.ReadToEnd();
stream.Close(); // End of stream.
// Going through the retrieved text.
using (StringReader reader = new StringReader(entireText))
{
string currentText = reader.ReadLine();
char[] splitIdentifier = { ' ' };
string[] brokenString;
while (currentText != null)
{
if (!currentText.StartsWith("f ") && !currentText.StartsWith("v ") && !currentText.StartsWith("vt ")
&& !currentText.StartsWith("vn "))
{
currentText = reader.ReadLine();
if (currentText != null)
{
currentText = currentText.Replace(" ", " ");
}
}
else
{
currentText = currentText.Trim(); // Trim the current line
brokenString = currentText.Split(splitIdentifier, 50); // Split the line into an array, separating the original line by blank spaces
switch (brokenString[0])
{
case "v":
vertices++;
break;
case "vt":
vt++;
break;
case "vn":
vn++;
break;
case "f":
face = face + brokenString.Length - 1;
triangles = triangles + 3 * (brokenString.Length - 2); /*brokenString.Length is 3 or greater since a face must have at least
3 vertices. For each additional vertice, there is an additional
triangle in the mesh (hence this formula).*/
break;
}
currentText = reader.ReadLine();
if (currentText != null)
{
currentText = currentText.Replace(" ", " ");
}
}
}
}
mesh.triangles = new int[triangles];
mesh.vertices = new Vector3[vertices];
mesh.uv = new Vector2[vt];
mesh.normals = new Vector3[vn];
mesh.faceData = new Vector3[face];
return mesh;
}
private static void populateMeshStruct(ref meshStruct mesh)
{
StreamReader stream = File.OpenText(mesh.fileName);
string entireText = stream.ReadToEnd();
stream.Close();
using (StringReader reader = new StringReader(entireText))
{
string currentText = reader.ReadLine();
char[] splitIdentifier = { ' ' };
char[] splitIdentifier2 = { '/' };
string[] brokenString;
string[] brokenBrokenString;
int f = 0;
int f2 = 0;
int v = 0;
int vn = 0;
int vt = 0;
int vt1 = 0;
int vt2 = 0;
while (currentText != null)
{
if (!currentText.StartsWith("f ") && !currentText.StartsWith("v ") && !currentText.StartsWith("vt ") &&
!currentText.StartsWith("vn ") && !currentText.StartsWith("g ") && !currentText.StartsWith("usemtl ") &&
!currentText.StartsWith("mtllib ") && !currentText.StartsWith("vt1 ") && !currentText.StartsWith("vt2 ") &&
!currentText.StartsWith("vc ") && !currentText.StartsWith("usemap "))
{
currentText = reader.ReadLine();
if (currentText != null)
{
currentText = currentText.Replace(" ", " ");
}
}
else
{
currentText = currentText.Trim();
brokenString = currentText.Split(splitIdentifier, 50);
switch (brokenString[0])
{
case "g":
break;
case "usemtl":
break;
case "usemap":
break;
case "mtllib":
break;
case "v":
mesh.vertices[v] = new Vector3(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2]),
System.Convert.ToSingle(brokenString[3]));
v++;
break;
case "vt":
mesh.uv[vt] = new Vector2(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2]));
vt++;
break;
case "vt1":
mesh.uv[vt1] = new Vector2(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2]));
vt1++;
break;
case "vt2":
mesh.uv[vt2] = new Vector2(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2]));
vt2++;
break;
case "vn":
mesh.normals[vn] = new Vector3(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2]),
System.Convert.ToSingle(brokenString[3]));
vn++;
break;
case "vc":
break;
case "f":
int j = 1;
List<int> intArray = new List<int>();
while (j < brokenString.Length && ("" + brokenString[j]).Length > 0)
{
Vector3 temp = new Vector3();
brokenBrokenString = brokenString[j].Split(splitIdentifier2, 3); //Separate the face into individual components (vert, uv, normal)
temp.x = System.Convert.ToInt32(brokenBrokenString[0]);
if (brokenBrokenString.Length > 1) //Some .obj files skip UV and normal
{
if (brokenBrokenString[1] != "") //Some .obj files skip the uv and not the normal
{
temp.y = System.Convert.ToInt32(brokenBrokenString[1]);
}
temp.z = System.Convert.ToInt32(brokenBrokenString[2]);
}
j++;
mesh.faceData[f2] = temp;
intArray.Add(f2);
f2++;
}
j = 1;
while (j + 2 < brokenString.Length) //Create triangles out of the face data. There will generally be more than 1 triangle per face.
{
mesh.triangles[f] = intArray[0];
f++;
mesh.triangles[f] = intArray[j];
f++;
mesh.triangles[f] = intArray[j+1];
f++;
j++;
}
break;
}
currentText = reader.ReadLine();
if (currentText != null)
{
currentText = currentText.Replace(" ", " "); //Some .obj files insert double spaces, this removes them.
}
}
}
}
}
void OnGUI()
{
GUI.Label (new Rect (20, 20, 100, 100), noOfLines.ToString());
}
}
This is a simple ProgressBar.cs I wrote:
using UnityEngine;
using System.Collections;
public class ProgressBar : MonoBehaviour {
float progress;
Vector2 pos;
Vector2 size;
public Texture2D barBG;
public Texture2D barLoad;
// Use this for initialization
void Start () {
progress = 0;
pos = new Vector2 (20, 40);
size = new Vector2 (100, 10);
}
// Update is called once per frame
void Update () {
progress = Time.time * 0.05f; // Place holder.
}
void OnGUI ()
{
GUI.DrawTexture(new Rect(pos.x, pos.y, size.x, size.y), barBG);
GUI.DrawTexture(new Rect(pos.x, pos.y, size.x * Mathf.Clamp01(progress), size.y), barLoad);
}
}
I have looked everywhere for a method in finding out progress completion of file reading+drawing of mesh and couldn't find one.
I've tried having the progressBar load respectively to the number of lines in the .obj file, but it isn't working too well as reading is way faster than the actual drawing of the mesh.
I'm out of ideas, anyone know of any way? Thanks in advance!

Categories