Unity3D transform.position.x keeps setting to 0 - c#

The weirdest thing keeps happening and I can not figure out why. Instead of just setting up like 20 different prefabs, I wanted to instatiate them in my code. I am making a Space Invaders C# game and I got the first row of invaders to spawn fine using the code found below. Literally no issues at all, and they move how I want them too as well. But as soon as I set up my second row the transform.position syntax that I used for the first row, suddenly does not apply and it just sets my transform.position.x to 0. I do have another class that MIGHT be the reason, but so far I have not found any solution to this problem. Thanks for help in advance.
//GameController Class
//
//globals
//
Quaternion roto;
public Vector3 newPos;
public float addInvader
bool spawnInvader = true;
public GameObject invaders;
//
void Update()
{
newPos = transform.position;
roto = transform.rotation;
newPos2 = transform.position;
roto2 = transform.rotation;
if (addInvader <= 0f)
{
SpawnInvaders ();
}
if (addInvader > 0f)
{
SpawnInvaders ();
}
if (addInvader > 5f)
{
spawnInvader = false;
}
if (add2Invader <= 0f)
{
//invaderSrow();
}
if (add2Invader > 0f)
{
//invaderSrow();
secondrow = false;
}
}
void SpawnInvaders()
{
if (spawnInvader)
{
if (addInvader < 1f)
{
newPos.x = 900f;
newPos.y = 0f;
newPos.z = 800f;
roto.z = 180f;
Instantiate (invaders, newPos, roto);
addInvader++;
}
if (addInvader == 1f)
{
newPos.x = 700f;
newPos.y = 0f;
newPos.z = 800f;
roto.z = 180f;
Instantiate (invaders, newPos, roto);
addInvader++;
}
if (addInvader == 2f)
{
newPos.x = 500f;
newPos.y = 0f;
newPos.z = 800f;
roto.z = 180f;
Instantiate (invaders, newPos, roto);
addInvader++;
}
if (addInvader == 3f)
{
newPos.x = 300f;
newPos.y = 0f;
newPos.z = 800f;
roto.z = 180f;
Instantiate (invaders, newPos, roto);
addInvader++;
}
if (addInvader == 4f)
{
newPos.x = 100f;
newPos.y = 0f;
newPos.z = 800f;
roto.z = 180f;
Instantiate (invaders, newPos, roto);
addInvader++;
}
if (addInvader == 5f)
{
newPos.x = -600f;
//newPos2.x = newPos2.x - 200f;
newPos.y = 0f;
newPos.z = 500f;
roto.z = 180f;
Instantiate (invaders, newPos, roto);
addInvader++;
}
}
return;
}
void invaderSrow()
{
InvaderController F = new InvaderController();
//F.newX = newPos2.x;
if (secondrow)
{
if (add2Invader < 1f)
{
newPos.x = -800f;
newPos.y = 0f;
newPos.z = 500f;
roto.z = 180f;
//Instantiate (invaders2, newPos, roto);
add2Invader++; //add2Invader should be 1 now....
//secondrow = false;
}
if (add2Invader == 1f)
{
newPos2 = transform.position;
newPos2.x = -800f + 200f;
//F.newX = -800f;
//F.newX = newPos2.x + 200f;
newPos2.y = 0f;
newPos2.z = 500f;
roto2.z = 180f;
//Instantiate (invaders3, newPos2, roto2);
add2Invader++;
}
}
return;
}
//InvaderController class
//
//globals
//
public float newX;
public float invaderSpeed;
public float resistance;
public GameObject Invader;
public GameObject explosion;
Quaternion rotation;
//
void Awake()
{
firstxoff = true;
}
// Update is called once per frame
void Update ()
{
if (firstxoff == true)
{
firstmove ();
}
moveX1 ();
}
void firstmove()
{
Vector3 newPos = transform.position;
newPos.x -= invaderSpeed;
transform.position = newPos;
if (newPos.x < -900f) //moves z
{
Vector3 newPosZ = transform.position;
newPosZ.z -= invaderSpeed;
float x = -900f;
newX = x;
newPosZ.x = newX;
transform.position = newPosZ;
}
}
void moveX1()
{
Vector3 newPos = transform.position;
if (newPos.z <= 500f)
{
Vector3 newPosX = transform.position;
newX = newX + invaderSpeed;
float z = 500f;
newZ = z;
newPosX.z = newZ;
newPosX.x = newX;
transform.position = newPosX;
if (newPosX.x > -900f)
{
newX = newX + (invaderSpeed + 7f);
firstxoff = false;
}
}
}

in moveX1() you are using newX , is it possible you are sometimes calling moveX1 before firstMove ? if so then newX would be undefined and 0.

Figured it out. Added a newX = newPosX.x; line at the start of my moveX1() function :D thanks everyone who tried!

Related

In Unity 3D my character's left foot does not react properly when walking, it looks wobbly when I walk around,any ideas?

The main character from the Unity 3D tutorials that I followed, I believe not from the site, are producing a wobbly left foot. I did not put a foot IK because the issue is not placement. It seems like an origin point thing, but not sure so I turned here for help.
I tried to have the full range of motion of the Mecanim character but was unable to produce foot bones on the rig that seem to work even though I just imported the model and code.
Third Person Character code :
using System;
using System.Collections;
using UnityEngine;
namespace UnityStandardAssets.Characters.ThirdPerson
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
[RequireComponent(typeof(Animator))]
public class ThirdPersonCharacter : MonoBehaviour
{
[SerializeField] float m_MovingTurnSpeed = 360;
[SerializeField] float m_StationaryTurnSpeed = 180;
[SerializeField] float m_JumpPower = 12f;
[Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f;
[SerializeField] float m_RunCycleLegOffset = 0.2f;
[SerializeField] float m_MoveSpeedMultiplier = 1f;
[SerializeField] float m_AnimSpeedMultiplier = 1f;
[SerializeField] float m_GroundCheckDistance = 0.1f;
Rigidbody m_Rigidbody;
Animator m_Animator;
bool m_IsGrounded;
float m_OrigGroundCheckDistance;
const float k_Half = 0.5f;
float m_TurnAmount;
float m_ForwardAmount;
Vector3 m_GroundNormal;
float m_CapsuleHeight;
Vector3 m_CapsuleCenter;
CapsuleCollider m_Capsule;
bool m_Crouching;
void Start()
{
m_Animator = GetComponent<Animator>();
m_Rigidbody = GetComponent<Rigidbody>();
m_Capsule = GetComponent<CapsuleCollider>();
m_CapsuleHeight = m_Capsule.height;
m_CapsuleCenter = m_Capsule.center;
m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
m_OrigGroundCheckDistance = m_GroundCheckDistance;
}
public void Move(Vector3 move, bool crouch, bool jump)
{
if (move.magnitude > 1f) move.Normalize();
move = transform.InverseTransformDirection(move);
CheckGroundStatus();
move = Vector3.ProjectOnPlane(move, m_GroundNormal);
m_TurnAmount = Mathf.Atan2(move.x, move.z);
m_ForwardAmount = move.z;
ApplyExtraTurnRotation();
if (m_IsGrounded)
{
HandleGroundedMovement(crouch, jump);
}
else
{
HandleAirborneMovement();
}
ScaleCapsuleForCrouching(crouch);
PreventStandingInLowHeadroom();
UpdateAnimator(move);
}
void ScaleCapsuleForCrouching(bool crouch)
{
if (m_IsGrounded && crouch)
{
if (m_Crouching) return;
m_Capsule.height = m_Capsule.height / 2f;
m_Capsule.center = m_Capsule.center / 2f;
m_Crouching = true;
}
else
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
m_Crouching = true;
return;
}
m_Capsule.height = m_CapsuleHeight;
m_Capsule.center = m_CapsuleCenter;
m_Crouching = false;
}
}
void PreventStandingInLowHeadroom()
{
if (!m_Crouching)
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
m_Crouching = true;
}
}
}
void UpdateAnimator(Vector3 move)
{
m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime);
m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime);
m_Animator.SetBool("Crouch", m_Crouching);
m_Animator.SetBool("OnGround", m_IsGrounded);
if (!m_IsGrounded)
{
m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y);
}
float runCycle =
Mathf.Repeat(
m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + m_RunCycleLegOffset, 1);
float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount;
if (m_IsGrounded)
{
m_Animator.SetFloat("JumpLeg", jumpLeg);
}
if (m_IsGrounded && move.magnitude > 0)
{
m_Animator.speed = m_AnimSpeedMultiplier;
}
else
{
m_Animator.speed = 1;
}
}
void HandleAirborneMovement()
{
Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity;
m_Rigidbody.AddForce(extraGravityForce);
m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f;
}
void HandleGroundedMovement(bool crouch, bool jump)
{
if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded"))
{
m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, m_JumpPower, m_Rigidbody.velocity.z);
m_IsGrounded = false;
m_Animator.applyRootMotion = false;
m_GroundCheckDistance = 0.1f;
}
}
void ApplyExtraTurnRotation()
{
float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount);
transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0);
}
public void OnAnimatorMove()
{
if (m_IsGrounded && Time.deltaTime > 0)
{
Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime;
v.y = m_Rigidbody.velocity.y;
m_Rigidbody.velocity = v;
}
}
void CheckGroundStatus()
{
RaycastHit hitInfo;
Debug.DrawLine(transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance));
if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance))
{
m_GroundNormal = hitInfo.normal;
m_IsGrounded = true;
m_Animator.applyRootMotion = true;
}
else
{
m_IsGrounded = false;
m_GroundNormal = Vector3.up;
m_Animator.applyRootMotion = false;
}
}
}

Float is going up slower after export

i want to multiply a float. in the unity editor everything is ok too, in the build it is going up slower all of a sudden.
i tried reimporting all assets and restart my pc but that does not help either.
I tried to build it again but that did not help.
I do not know what to do now, does anyone know how to fix this problem?
here is my build output: https://i.stack.imgur.com/ry5PI.png
code:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
[Header("")]
[Header("Move Settings")]
[Header("")]
public float MovementSpeed = 5f;
public float SprintSpeed = 7f;
public float JumpForce = 5f;
public float minJumpForce = 3f;
[Header("")]
[Header("Stamina Settings")]
[Header("")]
public float fillStamina = 1f;
public float MaxStamina = 10000f;
public float Stamina = 10000f;
public Slider staminaBar;
public GameObject SliderFill;
public GameObject SliderB;
[Header("")]
[Header("Health Settings")]
[Header("")]
public float fillHealth = 1f;
public float MaxHealth = 100f;
public float Health = 100f;
public Slider HealthBar;
[Header("")]
[Header("Player Settings")]
[Header("")]
Rigidbody2D body;
public static PlayerController instance;
public GameObject DeathObj;
float horizontal;
float vertical;
private Rigidbody2D _rigidbody;
private bool Sprint = false;
//private bool ActivateLowStamina = false;
//private bool LowStamina = false;
private float move;
private void Awake()
{
instance = this;
}
void Start()
{
_rigidbody = GetComponent<Rigidbody2D>();
//body = GetComponent<Rigidbody2D>();
Stamina = MaxStamina;
staminaBar.maxValue = MaxStamina;
staminaBar.value = MaxStamina;
HealthBar.maxValue = MaxHealth;
HealthBar.value = MaxHealth;
//ActivateLowStamina = false;
//lowTxt.gameObject.SetActive(false);
}
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
vertical = Input.GetAxisRaw("Vertical");
//transform.rotation = Quaternion.identity;
staminaBar.value = Stamina;
HealthBar.value = Health;
//var movement = Input.GetAxis("Horizontal");
if (Health < 1)
{
Die();
}
if (Stamina <= 0)
{
Stamina = 0;
}
if(Health <= 0)
{
Health = 0;
}
if (Stamina < 3000)
{
SliderFill.GetComponent<Image>().color = new Color32(213, 217, 0, 255);
SliderB.GetComponent<Image>().color = new Color32(11, 217, 0, 47);
}
else
{
SliderFill.GetComponent<Image>().color = new Color32(11, 217, 0, 255);
SliderB.GetComponent<Image>().color = new Color32(0, 255, 12, 47);
}
if (Input.GetKey("left shift"))
{
Sprint = true;
}
//if(Stamina < 100)
//{
// ActivateLowStamina = false;
//}
//else
//{
// ActivateLowStamina = true;
//}
//if(ActivateLowStamina == true)
// {
// lowTxt.gameObject.SetActive(true);
// }
if (Mathf.Abs(_rigidbody.velocity.x) == 0f && Stamina < MaxStamina && Mathf.Abs(_rigidbody.velocity.y) == 0f)
{
Stamina += fillStamina;
}
Health += fillHealth;
if (Input.GetButtonDown("Jump") && Mathf.Abs(_rigidbody.velocity.y) < 0.001f) {
if(Stamina > 10)
{
_rigidbody.AddForce(new Vector2(0, JumpForce), ForceMode2D.Impulse);
//_rigidbody.AddForce(Vector2.up * JumpForce);
UseStamina(700);
}
else
{
_rigidbody.AddForce(new Vector2(0, minJumpForce), ForceMode2D.Impulse);
//_rigidbody.AddForce(Vector2.up * JumpForce);
UseStamina(300);
}
}
}
public void UseStamina(float amount)
{
if (Stamina - amount >= 0)
{
Stamina -= amount;
}
}
private void FixedUpdate()
{
move = Input.GetAxis("Horizontal");
if (Sprint == true && Stamina > 10)
{
_rigidbody.velocity = new Vector2(move * SprintSpeed, _rigidbody.velocity.y);
if (Mathf.Abs(_rigidbody.velocity.x) != 0f)
{
UseStamina(10);
}
Sprint = false;
}
else
{
if (Stamina > 10)
{
_rigidbody.velocity = new Vector2(move * MovementSpeed, _rigidbody.velocity.y);
if(Mathf.Abs(_rigidbody.velocity.x) != 0f)
{
UseStamina(2f);
}
}
else
{
_rigidbody.velocity = new Vector2(move * 1f, _rigidbody.velocity.y);
}
}
//if(Mathf.Abs(_rigidbody.velocity.x) != 0f)
//{
//Stamina -= 1;
//}
}
public void Die()
{
if(Health < 1)
{
Time.timeScale = 0;
DeathObj.SetActive(true);
//SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
}
//_rigidbody.velocity = new Vector2(horizontal * MovementSpeed, vertical * SprintSpeed);
//transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * SprintSpeed;
//transform.Translate(new Vector3(-3f, 0, 0) * Time.deltaTime);
//_rigidbody.velocity = new Vector2(MovementSpeed, 0);
//_rigidbody.AddForce(new Vector2(MovementSpeed, MovementSpeed));
//transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * MovementSpeed;
//_rigidbody.velocity = new Vector2(horizontal * MovementSpeed, vertical * MovementSpeed);
//transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * 3f;
//body.velocity = new Vector2(horizontal * MovementSpeed, vertical * MovementSpeed);
//var movement = Input.GetAxis("Horizontal"); ```
What you experience is the typical frame-rate dependent code.
Every frame you do
Stamina += fillStamina;
and
Health += fillHealth;
However, what if on one device you have 60 frames per second, on another weaker device only 30?
On the weaker device it will take twice as long to raise the value.
Therefore you should use Time.deltaTime which is the time passed since the last frame was rendered.
By multiplying
X * Time.deltaTime
you convert a value X from value per frame into a value per second which is now independent of the capacity of the device and the frame-rate. Across all devices it will now always take the same effective time in seconds.
You will of course have to tweak your values but in general you would do e.g.
Stamina += fillStaminaPerSecond * Time.deltaTime;
and accordingly
Health += fillHealthPerSecond * Time.deltaTime;
And accordingly also for the continous usages
UseStamina(10 * Time.deltaTime);
and
UseStamina(2f * Time.deltaTime);
as said you might have to adjust the values since now they are more or less decided by 60 (whatever the frame-rate is).
However, for the single event calls for the jump you do not want/need the Time.deltaTime since these are no continous calls.
Btw instead of using GetComponent over and over again rather do it once in Awake or Start and store the reference in a field and later reuse it!
And instead of
[Header("")]
you should probably rather use
[Space]
;)

Unity HingeJoint have weird behavior in autogeneration problem with rotation?

I am a beginner and I have cube in air with element attached him with no rotation like a node, i have a couple cubes for simulate rope with hint joint. I have clicking right click at a cube and spawn rope from direction player to node and attaching last element rope with player and this working very well. When player doesn't have velocity, and blocked rotation on rigidbody elements. But sometimes if I have been jumped and try to spawn rope in moving elements rope have weird rotations, and sometimes cubes rotation blocks. How could I work with rotations rope or I don't know, any advice? Thanks.
PS: sorry for my bad English.
private void CheckMouseActivity()
{
float x = Input.mousePosition.x;
float y = Input.mousePosition.y;
float z = Input.mousePosition.z;
Vector3 point = new Vector3(x, y, z);
if (Input.GetMouseButton(1) && !m_ropeIsActive)
{
m_aiming = true;
Ray ray = Camera.main.ScreenPointToRay(point);
GenerateRope(ray);
}
if (Input.GetButton("Jump") && m_ropeIsActive)
{
for (int i = 0; i < rope.Count; i++)
{
DestroyImmediate(rope[i]);
//rope[i].active = false;
}
playerRb.AddForce(new Vector3(6f, 6f), ForceMode.Impulse);
m_ropeIsActive = false;
m_hooked = false;
}
// check bounds in playing area
}
void GenerateRope(Ray ray)
{
layerMask = ~layerMask;
if (Physics.Raycast(ray, out RaycastHit hit, 10f, layerMask))
{
if (hit.transform.CompareTag("node") && !m_ropeIsActive)
{
activeHook = hit.transform.gameObject;
m_CanMove = false;
Vector3 hitPos = hit.transform.position;
Transform hook = hit.transform.GetChild(0);
Vector3 hookInverseNormal = hook.up * -1f;
Rigidbody previosRb = hit.transform.GetChild(0).GetComponent<Rigidbody>();//hook
Vector3 distanceFromNode = transform.position - hit.point;
int distance = (int)distanceFromNode.magnitude;
BoxCollider link = linkPrefub.GetComponent<BoxCollider>();
int length = (int)((distance - 1f) / sizeCell);
float ropeLength = sizeCell * 10f;
if (length < minLength)
{
length = minLength;
}
//else if (length > ropeLength)
//{
// length = (int)ropeLength * 2;
//}
for (int i = 1; i < length - 1; i++)
{
var t = sizeCell * i; //позиция под новый куб
Vector3 dirToPlayer = transform.position - hit.transform.position;
Vector3 newPos = dirToPlayer.normalized * t;
GameObject toInstantiate = Instantiate(linkPrefub, hit.transform.position + new
Vector3(newPos.x, -t, default), Quaternion.identity, hit.transform);
rope.Add(toInstantiate);
HingeJoint joint = toInstantiate.GetComponent<HingeJoint>();
if (i == 1)
{
joint.autoConfigureConnectedAnchor = true;
}
else
{
joint.autoConfigureConnectedAnchor = false;
joint.connectedAnchor = new Vector3(0f, -0.4f);
}
joint.enableCollision = false;
joint.connectedBody = previosRb;
previosRb = toInstantiate.GetComponent<Rigidbody>();
}
m_ropeIsActive = true;
m_hooked = true;
m_CanMove = true;
}
}
else
{
// what to do if not did hit
}
}
void FixedUpdate()
{
if (m_ropeIsActive)
{
if (m_hooked && activeHook)
{
//TODO крутить нод хука чтобы выглядило красиво
}
if (rope.Count != 0)
{
Rigidbody lastElementRope = rope[rope.Count - 1].GetComponent<Rigidbody>();
if (lastElementRope)
{
HingeJoint joint = GetComponent<HingeJoint>();
//joint.autoConfigureConnectedAnchor = false;
//joint.connectedBody = lastElementRope;
//joint.anchor = Vector2.zero;
//joint.connectedAnchor = new Vector2(0f, -0.4f);
}
}
}
}
Can put code from github with project.
I experimented here trying to achieve obedience, but I am convinced that this is the wrong direction, I just do not know how to work with rotations, I got confused
if (i == 1)
{
joint.autoConfigureConnectedAnchor = true;
}
else
{
joint.autoConfigureConnectedAnchor = false;
joint.connectedAnchor = new Vector3(0f, -0.4f);
}
GitHub https://github.com/Heges/first-2d-platformer/tree/main/2D-platformer
i am not sure but
void GenerateRope(Ray ray)
{
layerMask = ~layerMask;
if (Physics.Raycast(ray, out RaycastHit hit, 10f, layerMask))
{
Vector3 direction = transform.position - hit.transform.position;
if (direction.magnitude <= sizeOfRope)
{
if (hit.transform.CompareTag("node") && !m_ropeIsActive)
{
activeHook = hit.transform.gameObject;
m_CanMove = false;
Transform hook = hit.transform.GetChild(0);
Vector3 hookInverseNormal = hook.up * -1f;
float dot = Vector3.Dot(hookInverseNormal, ray.direction.normalized);
Debug.Log(dot);
Quaternion rotation = hit.transform.rotation;
Rigidbody previosRb = hit.transform.GetChild(0).GetComponent<Rigidbody>();//hook
Vector3 distanceFromNode = transform.position - hit.point;
int distance = (int)distanceFromNode.magnitude;
BoxCollider link = linkPrefub.GetComponent<BoxCollider>();//(int)link.size.magnitude / 2;
int length = (int)((distance - 1f) / sizeCell); //size of cell rope -1f размер игрока
float ropeLength = sizeCell * sizeOfRope;
if (length < minLength)
{
length = minLength;
}
//else if (length > ropeLength) // и слишком длинных
//{
// length = (int)ropeLength * 2;
//}
for (int i = 1; i < length - 1; i++)
{
var t = sizeCell * i; //позиция под новый куб
Vector3 dirToPlayer = transform.position - hit.transform.position;//направление до игрока,
Vector3 newPos = dirToPlayer.normalized * t;
GameObject toInstantiate = Instantiate(linkPrefub, hit.transform.position + new Vector3(newPos.x, -t, default), Quaternion.identity, hit.transform);
rope.Add(toInstantiate);
HingeJoint joint = toInstantiate.GetComponent<HingeJoint>();
joint.anchor = Vector2.up;
joint.connectedAnchor = new Vector2(0f, -0.4f);
joint.connectedBody = previosRb;
previosRb = toInstantiate.GetComponent<Rigidbody>();
}
m_ropeIsActive = true;
m_hooked = true;
}
}
else
{
//what to do if not did hit
}
}
it is still don't work very well but.like my problem is solved.
limited the distance from which the rope can be summoned, and as it turned out, when autogenerating parts of the rope, the Hint Joint defaults to its values ​​such as AutoAnchor. disabling them during creation, it seems that everything seems to work as it should
HingeJoint joint = toInstantiate.GetComponent<HingeJoint>();
joint.anchor = Vector2.up;
joint.connectedAnchor = new Vector2(0f, -0.4f);
joint.connectedBody = previosRb;
previosRb = toInstantiate.GetComponent<Rigidbody>();

How do I fix my 2D enemy character from sliding instead of stopping when it gives a warning when a character is near to it's range

In game overview
I am still new to C#, and I wanted to know how to fix this problem. The enemy skeleton seems to slide when it reaches the range of the character. I tried finding the solution but failed to do so.
------------------------------ENEMY SCRIPT--------------------------------
private Rigidbody2D myBody;
[Header("Movement")]
public float moveSpeed;
private float minX, maxX;
public float distance;
public int direction;
private bool patrol, detect;
private Transform playerPos;
private Animator anim;
[Header("Attack")]
public Transform attackPos;
public float attackRange;
public LayerMask playerLayer;
public int damage;
AWAKE
void Awake()
{
anim = GetComponent<Animator>();
playerPos = GameObject.Find("George").transform;
myBody = GetComponent<Rigidbody2D>();
}
VOID START
private void Start()
{
maxX = transform.position.x + (distance);
minX = maxX - distance;
//if (Random.value > 0.5) direction = 1;
//else direction = -1;
}
UPDATE
void Update()
{
if (Vector3.Distance(transform.position, playerPos.position) <= 4.0f) patrol = false;
else patrol = true;
}
FIXED UPDATE
private void FixedUpdate()
{
if (anim.GetBool("Death"))
{
myBody.velocity = Vector2.zero;
GetComponent<Collider2D>().enabled = false;
myBody.isKinematic = true;
anim.SetBool("Attack", false);
return;
}
if (myBody.velocity.x > 0)
{
transform.localScale = new Vector2(1f, transform.localScale.y);
anim.SetBool("Attack", false);
}
else if
(myBody.velocity.x < 0) transform.localScale = new Vector2(-1f, transform.localScale.y);
if (patrol)
{
detect = false;
switch (direction)
{
case -1:
if (transform.position.x > minX)
myBody.velocity = new Vector2(-moveSpeed, myBody.velocity.y);
else
direction = 1;
break;
case 1:
if (transform.position.x < maxX)
myBody.velocity = new Vector2(moveSpeed, myBody.velocity.y);
else
direction = -1;
break;
}
}
else
{
if (Vector2.Distance(playerPos.position, transform.position) >= 1.0f)
{
if (!detect)
{
detect = true;
anim.SetTrigger("Detect");
myBody.velocity = new Vector2(0, myBody.velocity.y);
}
if (anim.GetCurrentAnimatorStateInfo(0).IsName("detect")) return;
Vector3 playerDir = (playerPos.position - transform.position).normalized;
if (playerDir.x > 0)
myBody.velocity = new Vector2(moveSpeed + 0.4f, myBody.velocity.y);
else
myBody.velocity = new Vector2(-(moveSpeed + 0.4f), myBody.velocity.y);
}
else if (Vector2.Distance(playerPos.position, transform.position) <= 1.0f)
{
myBody.velocity = new Vector2(0, myBody.velocity.y);
anim.SetBool("Attack", true);
}
}
}

Instantiate overload not sure why

So when I instantiated invaders it worked when i did 2 of them, but as soon as i tried to instantiate more than 2 (created a variable float addInvaders, and an if statement if addInvader is equal to 5) my game literally just crashes. It runs for a second, and I see it create like a million invaders then it Unity doesn't respond anymore. Wondering what I'm doing wrong, and what I can do to fix. I think this is all the code you need, please let me know I'll add additional code if need be.
//globals
float addInvader = 0f;
bool spawnInvader = true;
public GameObject invaders;
void Update()
{
SpawnInvaders ();
while (addInvader == 5f)
{
spawnInvader = false;
}
}
void SpawnInvaders()
{
if (spawnInvader)
{
Vector3 newPos = transform.position;
Quaternion roto = transform.rotation;
newPos.x = 900f;
newPos.y = 0f;
newPos.z = 800f;
roto.z = 180f;
Instantiate (invaders, newPos, roto);
addInvader++;
if (addInvader >= 1f)
{
newPos.x = newPos.x - 200f;
newPos.y = 0f;
newPos.z = 800f;
roto.z = 180f;
Instantiate (invaders, newPos, roto);
}
}
return;
}
I don't have enough reputation to comment so I'll try to answer instead.
It appears you created an infinite loop :
while (addInvader == 5f)
{
spawnInvader = false;
}
Change it to :
if (addInvader >= 5f)
{
spawnInvader = false;
}
It should stop crashing.

Categories

Resources