- Home /
sprite changes z position without any input to do so
im making a 2d platformer and i have a patrolling enemy but for some reason he changes z position even though i didn't say to and it makes his z position behind the camera so he doesn't render
heres the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyPatrol : MonoBehaviour {
public float speed;
public float distance;
private bool movingRight = true;
public Transform groundDetection;
void Update()
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, distance);
if (groundInfo.collider == false)
{
if (movingRight == true)
{
transform.eulerAngles = new Vector3(0, -180, 0);
movingRight = false;
}else
{
transform.eulerAngles = new Vector3(0, 0, 0);
movingRight = true;
}
}
}
}
i kinda fixed it(by deleting the sprite and putting in a new one). i say kinda because even tho the z position is still changing in the inspector, he isnt actually changing z in the scene or game.
Hi , when the z is changing in inspector , it also changing in scene forsure. i think your problem is that you add rigidbody to your player add dont mark the constraint checkbox for z position. also add Space.world to your second parameter of translate if you are in world space.
Answer by toddisarockstar · Sep 09, 2018 at 12:38 PM
try this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyPatrol : MonoBehaviour {
public float speed;
public float distance;
private bool movingRight = true;
public Transform groundDetection;
void Update()
{
transform.position = new Vector3(transform.position.x+ speed *Time.deltaTime,
transform.position.y,transform.position.z);
);
RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, distance);
if (groundInfo.collider == false)
{
if (movingRight == true)
{
transform.eulerAngles = new Vector3(0, -180, 0);
movingRight = false;
}else
{
transform.eulerAngles = new Vector3(0, 0, 0);
movingRight = true;
}
}
}
}
Your answer
Follow this Question
Related Questions
Enemy keeps moving in one direction. Help pls! 2 Answers
Boss Health Bar 1 Answer
Enemy's initial attack doesn't deal damage to player 1 Answer
Enemy AI Help,Help on EnemyAI 2D 0 Answers