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;
}
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.
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)"