[ad_1]
utilizing UnityEngine;
public class AlienMovement : MonoBehaviour
{
[SerializeField]
non-public float screenBorder = 30;
public float moveSpeed = 1.0f;
public Rigidbody2D rb;
public float maxVariability = 4.0f;
public float minVariability = -4.0f;
non-public Digital camera camera1;
non-public void Begin()
{
camera1 = Digital camera.primary;
// Generate a random variability throughout the specified vary
float variability = Random.Vary(minVariability, maxVariability);
// Set the rate based mostly on variability
rb.velocity = new Vector2(variability, 0) * moveSpeed;
}
non-public void FixedUpdate()
{
reverseVelocity();
}
/*
* Checks if the Alien is close to the border
* Adjustments the course to the other method if the Alien hits the border
*/
non-public void reverseVelocity()
{
Vector2 screenPosition = camera1.WorldToScreenPoint(rb.place);
if ((screenPosition.x < screenBorder) || (screenPosition.x > camera1.pixelWidth - screenBorder))
{
//Reverses the course
rb.velocity = new Vector2(-rb.velocity.x, 0);
}
}
}
utilizing UnityEngine;
public class Boundaries : MonoBehaviour
{
public Digital camera MainCamera;
public Vector2 screenBounds { get; non-public set; }
non-public float objectWidth;
non-public float objectHeight;
// Use this for initialization
void Begin()
{
MainCamera = FindObjectOfType<Digital camera>();
screenBounds = MainCamera.ScreenToWorldPoint(new Vector3(Display.width, Display.peak, MainCamera.rework.place.z));
objectWidth = rework.GetComponent<SpriteRenderer>().bounds.extents.x; //extents = measurement of width / 2
objectHeight = rework.GetComponent<SpriteRenderer>().bounds.extents.y; //extents = measurement of peak / 2
}
// Replace known as as soon as per body
void LateUpdate()
{
Vector3 viewPos = rework.place;
viewPos.x = Mathf.Clamp(viewPos.x, screenBounds.x * -1 + objectWidth, screenBounds.x - objectWidth);
viewPos.y = Mathf.Clamp(viewPos.y, screenBounds.y * -1 + objectHeight, screenBounds.y - objectHeight);
rework.place = viewPos;
}
}
Within the Unity editor, the code works, permitting the alien to reverse their velocity when it touches the border. Nevertheless, the alien is caught on the border after constructing the sport.
[ad_2]