Lerp between point on LineRenderer - unity3d

Im stuck on how to lerp between points of the linerenderer which are added on runtime. It should animate in order. So IEnumerator should be used i guess.
private void makeLine(Transform finalPoint)
{
if(lastPoints == null)
{
lastPoints = finalPoint;
points.Add(lastPoints);
}
else
{
points.Add(finalPoint);
lr.enabled = true;
SetupLine();
}
}
private void SetupLine()
{
int pointLength = points.Count;
lr.positionCount = pointLength;
for (int i = 0; i < pointLength; i++)
{
lr.SetPosition(i, points[i].position);
// StartCoroutine(AnimateLine());
}
}
I found a code example. But now sure how to implement it so it would fit the code above:
private IEnumerator AnimateLine()
{
//coroutinIsDone = false;
float segmentDuration = animationDuration / points.Count;
for (int i = 0; i < points.Count - 1; i++)
{
float startTime = Time.time;
Vector3 startPosition = points[i].position;
Vector3 endPosition = points[i + 1].position;
Vector3 pos = startPosition;
while (pos != endPosition)
{
float t = (Time.time - startTime) / segmentDuration;
pos = Vector3.Lerp(startPosition, endPosition, t);
for (int j = i + 1; j < points.Count; j++)
lr.SetPosition(j, pos);
yield return null;
}
}
}

Related

GetPixel makes the game slow

I'm creating a cleaning game but in the getpixel line of code makes the game slow or having a delay. I need this line of code to detect the remaining dirt. How can I improve the code? or is there other way to detect remaining dirt?
private void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
if (touch.position != currentPosition || touch.position != prevPosition)
{
SetSinglePixel(touch.position);
prevPosition = touch.position;
}
}
else if (touch.phase == TouchPhase.Moved)
{
if (touch.position != currentPosition || touch.position != prevPosition)
{
currentPosition = touch.position;
Vector2 dif = currentPosition - prevPosition;
float distance = dif.magnitude;
if (distance > 36)
{
float count = distance / 36;
float n = distance / (count + 1);
float ddmo = 36;
for (int i = 0; i <= count; i++)
{
Vector2 gapPoint = Vector2.MoveTowards(prevPosition, currentPosition, ddmo * i);
if (Physics.Raycast(Camera.main.ScreenPointToRay(gapPoint), out RaycastHit hit))
{
gapPositions.Add(hit.textureCoord);
}
}
SetMultiplePixel(gapPositions);
gapPositions.Clear();
}
else
{
SetSinglePixel(currentPosition);
}
prevPosition = touch.position;
}
}
}
}
private void SetMultiplePixel(List<Vector2> givenPoints)
{
foreach (Vector2 pos in givenPoints)
{
SetPixel(pos.x, pos.y);
}
}
private void SetSinglePixel(Vector2 touchPos)
{
if (Physics.Raycast(Camera.main.ScreenPointToRay(touchPos), out RaycastHit hit))
{
SetPixel(hit.textureCoord.x, hit.textureCoord.y);
}
}
public void ResetTexture()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
private void SetPixel(float textureCoordX, float textureCoordY, bool isCheckRemainingTexture = false)
{
int pixelX = (int)(textureCoordX * _templateDirtMask.width);
int pixelY = (int)(textureCoordY * _templateDirtMask.height);
int pixelXOffset = pixelX - (_brush.width / 2);
int pixelYOffset = pixelY - (_brush.height / 2);
for (int x = 0; x < _brush.width; x++)
{
for (int y = 0; y < _brush.height; y++)
{
data = (pixelXOffset + x) + (pixelYOffset + y) * _templateDirtMask.width;
if (data > 0 && data < pixels.Length)
{
pixelDirt = _brush.GetPixel(x, y);// this code makes the game slow
Color pixelDirtMask = _templateDirtMask.GetPixel(pixelXOffset + x, pixelYOffset + y); // this code makes the game slow
float removedAmount = pixelDirtMask.g - (pixelDirtMask.g * pixelDirt.g);
dirtAmount -= removedAmount;
pixels[data] = new Color(0, pixelDirtMask.g * pixelDirt.g, 0);
}
}
}
ApplyTexture();
}

Zooming limit in unity mobile. Perspective Camera

I'm trying to limit the zoom value of my game to a minimum and a maximum but i can't get how to do it!
I've been trying by limiting the Y according to the zoom factor but it does not work properly, because when it reaches the limit, it starts flickering, like it hit an obstacle. I found some things that can solve this problem by using the fieldofview, but I need it to work with the Y limitations!
I also want to add a panning limit, so that the player won't be able to see the end of the map but I didn't get there yet.
Anyways, here is the code i'm using and would appreciate if someone could help!
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
class ScrollAndPinch : MonoBehaviour
{
#if UNITY_IOS || UNITY_ANDROID
public Camera Camera;
public bool Rotate;
protected Plane Plane;
public float scrollSpeed;
public float rotateSpeed;
public float zoomSpeed;
public float zoomMinY;
public float zoomMaxY;
public float camsummer;
Vector3 pos;
private Vector3 velocity = Vector3.zero;
private void Awake()
{
if (Camera == null)
Camera = Camera.main;
Rotate = true;
scrollSpeed = 50f;
rotateSpeed = 50f;
zoomSpeed = 1f;
zoomMinY = 50f;
zoomMaxY = 200f;
camsummer = 0.1f;
pos = new Vector3(0f, 0f, 0f);
}
private void Update()
{
//Update Plane
if (Input.touchCount >= 1)
Plane.SetNormalAndPosition(transform.up, transform.position);
var Delta1 = Vector3.zero;
var Delta2 = Vector3.zero;
//Scroll
if (Input.touchCount == 1)
{
Delta1 = PlanePositionDelta(Input.GetTouch(0));
if (Input.GetTouch(0).phase == TouchPhase.Moved)
Camera.transform.Translate(Delta1 * scrollSpeed * Time.deltaTime, Space.World);
}
//Pinch
if (Input.touchCount == 2)
{
var pos1 = PlanePosition(Input.GetTouch(0).position);
var pos2 = PlanePosition(Input.GetTouch(1).position);
var pos1b = PlanePosition(Input.GetTouch(0).position - Input.GetTouch(0).deltaPosition);
var pos2b = PlanePosition(Input.GetTouch(1).position - Input.GetTouch(1).deltaPosition);
//calc zoom to be done relative to the distance moved between the fingers
var zoom = (Vector3.Distance(pos1, pos2) /
Vector3.Distance(pos1b, pos2b));
//edge case (Bad calculation)
if (zoom == 0 || zoom > 10)
return;
//Move cam amount the mid ray. This is where the zoom is applied
// Vector3 pos = Camera.transform.position;
// pos.y = Mathf.Clamp(pos.y, zoomMinY, zoomMaxY);
// Camera.transform.position = Vector3.Lerp(pos1, Camera.transform.position, (1 / zoom));
// Camera.transform.position = pos;
if (Camera.transform.position.y < zoomMinY | Camera.transform.position.y > zoomMaxY)
{
// Camera.transform.position = pos;
Camera.transform.position = Vector3.SmoothDamp(Camera.transform.position, pos, ref velocity, camsummer);
// Camera.transform.position = Vector3.LerpUnclamped(Camera.transform.position, pos, camsummer);
// for (int i = 0; i < 1000; i++)
// {
// }
}
else if (Camera.transform.position.y >= zoomMinY && Camera.transform.position.y <= zoomMaxY)
{
pos = Camera.transform.position;
Camera.transform.position = Vector3.LerpUnclamped(pos1, Camera.transform.position, (1 / zoom));
//This is where the rotation is applied
if (Rotate && pos2b != pos2)
Camera.transform.RotateAround(pos1, Plane.normal,
Vector3.SignedAngle(pos2 - pos1, pos2b - pos1b, Plane.normal) * rotateSpeed * Time.deltaTime);
}
// pos.y = zoomMinY;
}
// if (Camera.transform.position.y > 200)
// {
// zoomMaxY.y = 200;
// Camera.transform.position = zoomMaxY;
// }
// else if (Camera.transform.position.y < 50)
// {
// zoomMinY.y = 50;
// Camera.transform.position = zoomMinY;
// }
// else if (Camera.transform.position.y >= 50 && Camera.transform.position.y <= 200)
// {
// Camera.transform.position = Vector3.LerpUnclamped(pos1, Camera.transform.position, (1 / zoom));
// }
// Vector3 Cam = Mathf.Clamp(Camera.transform.position.y, zoomMinY.y, zoomMaxY.y);
// if (Camera.transform.position.y > zoomMaxY || Camera.transform.position.y < zoomMinY)
// {
// Vector3 camLimit = Camera.transform.position;
// camLimit.y = Mathf.Clamp(Camera.transform.position.y, zoomMinY, zoomMaxY);
// Camera.transform.position = camLimit;
// // Vector3 camLimit = Camera.transform.position;
// // camLimit = (transform.position.);
// // Camera.transform.position = camLimit;
// }
// else if (Camera.transform.position.y >= zoomMinY && Camera.transform.position.y <= zoomMaxY)
// {
// Camera.transform.position = Vector3.LerpUnclamped(pos1, Camera.transform.position, (1 / zoom));
// }
}
protected Vector3 PlanePositionDelta(Touch touch)
{
//not moved
if (touch.phase != TouchPhase.Moved)
return Vector3.zero;
//delta: How far have we moved from A to B by sliding the finger
var rayBefore = Camera.ScreenPointToRay(touch.position - touch.deltaPosition);
var rayNow = Camera.ScreenPointToRay(touch.position);
if (Plane.Raycast(rayBefore, out var enterBefore) && Plane.Raycast(rayNow, out var enterNow))
return rayBefore.GetPoint(enterBefore) - rayNow.GetPoint(enterNow);
//not on plane
return Vector3.zero;
}
protected Vector3 PlanePosition(Vector2 screenPos)
{
//position
var rayNow = Camera.ScreenPointToRay(screenPos);
if (Plane.Raycast(rayNow, out var enterNow))
return rayNow.GetPoint(enterNow);
return Vector3.zero;
}
private void OnDrawGizmos()
{
Gizmos.DrawLine(transform.position, transform.position + transform.up);
}
#endif
}
And to make it easier to see, this is the part I am struggling to make it work.
if (Camera.transform.position.y < zoomMinY | Camera.transform.position.y > zoomMaxY)
{
Camera.transform.position = Vector3.SmoothDamp(Camera.transform.position, pos, ref velocity, camsummer);
}
else if (Camera.transform.position.y >= zoomMinY && Camera.transform.position.y <= zoomMaxY)
{
pos = Camera.transform.position;
Camera.transform.position = Vector3.LerpUnclamped(pos1, Camera.transform.position, (1 / zoom));
//This is where the rotation is applied
if (Rotate && pos2b != pos2)
Camera.transform.RotateAround(pos1, Plane.normal,
Vector3.SignedAngle(pos2 - pos1, pos2b - pos1b, Plane.normal) * rotateSpeed * Time.deltaTime);
}
Does this happen when the camera gets close to an object?
If so change the near clip plane distance on your camera to.near = 0
That should stop it from not showing the gameobject, if ur camera keeps moving it might cause the flickering because it clips in and out of the near clip plane

My playable character turns left or right when it meets an obstacle

My playable character turns left or right when it meets an obstacle with a collider. It's normal but I want to know if there is a way to disable it.
this is the script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMotor : MonoBehaviour
{
public Vector3 startPosition;
private const float LANE_DISTANCE = 3.0f;
private const float TURN_SPEED = 0.5f;
//Functionality
private bool isRunning = false;
public bool isClimbing = false;
private readonly object down;
private CharacterController controller;
[SerializeField]
private float jumpForce = 5.0f;
private float verticalVelocity = 0.0f;
private float gravity = 10.0f;
//Speed
private float originalSpeed = 4.0f;
private float speed = 4.0f;
private float speedIncreaseLastTick;
private float speedIncreaseTime = 2.5f;
private float speedIncreaseAmount = 0.1f;
private float climbingSpeed = 1.0f;
private int desiredLane = 0; //0 = left, 1 = middle, 2 = right
private Animator anim;
// Start is called before the first frame update
void Start()
{
speed = originalSpeed;
controller = GetComponent<CharacterController>();
anim = GetComponent<Animator>();
transform.position = startPosition;
}
// Update is called once per frame
void Update()
{
if (isClimbing)
{
transform.Translate(Vector3.up * climbingSpeed * Time.deltaTime);
}
if (!isRunning)
return;
if (Time.time - speedIncreaseLastTick > speedIncreaseTime)
{
speedIncreaseLastTick = Time.time;
speed += speedIncreaseAmount;
//GameManager.Instance.UpdateScores();
}
// Gather the inputs on wich lane we should be
if (MobileInput.Instance.SwipeLeft)
{
MoveLane(false);
}
if (MobileInput.Instance.SwipeRight)
{
MoveLane(true);
}
// Calculate where we should be horizontally
Vector3 targetPosition = transform.position.z * Vector3.forward;
int posX = Mathf.Abs(desiredLane);
if (desiredLane < 0)
targetPosition += Vector3.left * posX * LANE_DISTANCE;
else if (desiredLane > 0)
targetPosition += Vector3.right * posX * LANE_DISTANCE;
//Calculate move delta
Vector3 moveVector = Vector3.zero;
moveVector.x = (targetPosition - transform.position).normalized.x * speed;
bool isGrounded = IsGrounded();
anim.SetBool("Grounded", isGrounded);
//Calculate y
if (isGrounded) //If grounded
{
verticalVelocity = -0.1f;
if (MobileInput.Instance.SwipeUp)
{
//Jump
anim.SetTrigger("Jump");
verticalVelocity = jumpForce;
}
else if (MobileInput.Instance.SwipeDown)
{
//Slide
StartSliding();
Invoke("StopSliding", 1.0f);
}
}
else
{
verticalVelocity -= (gravity * Time.deltaTime);
//Fast falling machanics
if (MobileInput.Instance.SwipeDown)
{
verticalVelocity = -jumpForce;
}
}
moveVector.y = verticalVelocity;
moveVector.z = speed;
//Move the character
controller.Move(moveVector * Time.deltaTime);
//Rotate the player where is going
Vector3 dir = controller.velocity;
if (dir!= Vector3.zero)
{
dir.y = 0;
transform.forward = Vector3.Lerp(transform.forward, dir, TURN_SPEED);
}
}
// This function (MoveLane) allows the player to move to the left and to the right
private void MoveLane(bool goingRight)
{
if (!goingRight)
{
desiredLane--;
if (desiredLane == -6)
desiredLane = -5;
}
if (goingRight)
{
desiredLane++;
if (desiredLane == 6)
desiredLane = 5;
}
/* We wan rewrite the above function like this below
desiredLane += (goingRight) ? 1 : -1;
Mathf.Clamp(desiredLane, -5, 5);
*/
}
private bool IsGrounded()
{
Ray groundRay = new Ray(new Vector3(controller.bounds.center.x, (controller.bounds.center.y - controller.bounds.extents.y) + 0.2f,
controller.bounds.center.z), Vector3.down);
Debug.DrawRay(groundRay.origin, groundRay.direction, Color.cyan, 1.0f);
return (Physics.Raycast(groundRay, 0.2f + 0.1f));
}
public void StartRunning ()
{
isRunning = true;
anim.SetTrigger("StartRunning");
}
private void StartSliding()
{
anim.SetBool("Sliding", true);
controller.height /= 2;
controller.center = new Vector3(controller.center.x, controller.center.y / 2, controller.center.z);
}
private void StopSliding()
{
anim.SetBool("Sliding", false);
controller.height *= 2;
controller.center = new Vector3(controller.center.x, controller.center.y * 2, controller.center.z);
}
private void Crash()
{
anim.SetTrigger("Death");
isRunning = false;
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
switch(hit.gameObject.tag)
{
case "Obstacle":
Crash();
break;
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Ladder")
{
isRunning = false;
isClimbing = true;
anim.SetBool("ClimbingLadder", true);
}
else if (other.gameObject.tag == "LadderCol2")
{
isClimbing = false;
anim.SetBool("ClimbingLadder", false);
transform.Translate(Vector3.forward * 1);
isRunning = true;
}
}
}
I see the problem. It's from these lines
Vector3 dir = controller.velocity;
if (dir!= Vector3.zero)
{ dir.y = 0;
transform.forward =
Vector3.Lerp(transform.forward, dir,
TURN_SPEED);
}
I added them to rotate a bit the player when it turns left or right.

Designing a specific grid movement

what I'm trying to achieve, is that while the player holds the mouse button
on a tile (any grid element, verically or horizontally aligned with the player), the player will move towards that tile with the possible directions of left,right,up,down only.
currently my code doesn't work for while pressing the mouse button, I think it has something to do with the raycasting.
second thing I want to achieve is that while the player is moving in the grid, if the player decides to change direction, he will be able, no matter if it's just opposite direction, or if he decideds to take a sudden turn left/right.
(I managed to achieve it without using the isMoving boolean condition only in the opposite direction, but I added it because when the player clicked while moving it slowed him down)
right now no change in movement while moving is available.
using UnityEngine;
using Holoville.HOTween;
using System.Collections;
public class Player : MonoBehaviour {
public float speed = 100f;
private Vector3 startPos;
private Vector3 endPos;
private float startTime;
private float journeyLength;
private tile currentTile;
private tile tileToMove;
private float angleToTurn = 0f;
private bool isMoving = false;
public static Player use;
void Awake()
{
use = this;
}
void Start () {
startPos = endPos = transform.position;
tileToMove = currentTile = fieldGenerator.use.tilesList[0];
}
// Update is called once per frame
void Update () {
MovePlayer();
float distCovered = (Time.time - startTime) * speed;
float fracJourney = distCovered / journeyLength;
if (!startPos.Equals(endPos))
transform.position = Vector3.Lerp(startPos, endPos, fracJourney);
if (transform.position == endPos)
{
isMoving = false;
}
}
void MovePlayer()
{
Ray ray;
RaycastHit hit;
if (Input.GetMouseButtonDown(0) && !isMoving)
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
for (int i = 0; i < fieldGenerator.use.tilesList.Count; i++)
{
if (fieldGenerator.use.tilesList[i].selfObject.collider.Raycast(ray, out hit, float.PositiveInfinity))
{
if (fieldGenerator.use.tilesList[i].selfObject.transform.position.x < transform.position.x && fieldGenerator.use.tilesList[i].selfObject.transform.position.y == transform.position.y)
{
angleToTurn = -180f;
tileToMove = fieldGenerator.use.tilesList[i];
isMoving = true;
}
else if (fieldGenerator.use.tilesList[i].selfObject.transform.position.x > transform.position.x && fieldGenerator.use.tilesList[i].selfObject.transform.position.y == transform.position.y)
{
angleToTurn = 0;
tileToMove = fieldGenerator.use.tilesList[i];
isMoving = true;
}
else if (fieldGenerator.use.tilesList[i].selfObject.transform.position.y < transform.position.y && fieldGenerator.use.tilesList[i].selfObject.transform.position.x == transform.position.x)
{
angleToTurn = -90f;
tileToMove = fieldGenerator.use.tilesList[i];
isMoving = true;
}
else if (fieldGenerator.use.tilesList[i].selfObject.transform.position.y > transform.position.y && fieldGenerator.use.tilesList[i].selfObject.transform.position.x == transform.position.x)
{
angleToTurn = 90f;
tileToMove = fieldGenerator.use.tilesList[i];
isMoving = true;
}
startTime = Time.time;
startPos = transform.position;
endPos = tileToMove.selfObject.transform.position;
journeyLength = Vector3.Distance(startPos, endPos);
transform.eulerAngles = new Vector3(0f, 0f, angleToTurn);
}
}
}
}
}
Unsure on what you're doing with the tiles and raycasting but here's how i'd do it. Apologies for the formatting, it's just how I work.
EDIT: Okay, given you said 'grid' movement I assumed the tiles were equidistant from each other. GetMouseButtonDown changed to GetMouseButton as well. This will mean that a ray is shot every update which you may want to look into making more efficient.
using UnityEngine;
using Holoville.HOTween;
using System.Collections;
public class Player : MonoBehaviour {
public float speed = 100.0f;
private float delta = 0.0f;
private float distance = 1.0f;
private Vector3 startPos;
private Vector3 endPos;
private tile currentTile;
private tile tileToMove;
private float angleToTurn = 0f;
private bool isMoving = false;
public static Player use;
void Awake() {
use = this;
}
void Start () {
startPos = endPos = transform.position;
tileToMove = currentTile = fieldGenerator.use.tilesList[0];
}
// Update is called once per frame
void Update () {
GetInput();
MovePlayer();
}
void MovePlayer() {
if ( isMoving ) {
if ( delta < 1 ) {
// Distance independant movement.
delta += ( speed/distance ) * Time.deltaTime;
transform.position = Vector3.Lerp(startPos, endPos, delta);
} else {
isMoving = false;
}
}
}
void GetInput() {
Ray ray;
RaycastHit hit;
if ( Input.GetMouseButton(0) ) {
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
for (int i = 0; i < fieldGenerator.use.tilesList.Count; i++) {
if ( fieldGenerator.use.tilesList[i].selfObject.collider.Raycast( ray, out hit, float.PositiveInfinity ) ) {
if (fieldGenerator.use.tilesList[i].selfObject.transform.position.x < transform.position.x && fieldGenerator.use.tilesList[i].selfObject.transform.position.y == transform.position.y) {
angleToTurn = -180f;
tileToMove = fieldGenerator.use.tilesList[i];
isMoving = true;
} else if (fieldGenerator.use.tilesList[i].selfObject.transform.position.x > transform.position.x && fieldGenerator.use.tilesList[i].selfObject.transform.position.y == transform.position.y) {
angleToTurn = 0;
tileToMove = fieldGenerator.use.tilesList[i];
isMoving = true;
} else if (fieldGenerator.use.tilesList[i].selfObject.transform.position.y < transform.position.y && fieldGenerator.use.tilesList[i].selfObject.transform.position.x == transform.position.x) {
angleToTurn = -90f;
tileToMove = fieldGenerator.use.tilesList[i];
isMoving = true;
} else if (fieldGenerator.use.tilesList[i].selfObject.transform.position.y > transform.position.y && fieldGenerator.use.tilesList[i].selfObject.transform.position.x == transform.position.x) {
angleToTurn = 90f;
tileToMove = fieldGenerator.use.tilesList[i];
isMoving = true;
}
isMoving = true;
delta = 0f;
startPos = transform.position;
endPos = tileToMove.selfObject.transform.position;
distance = Vector3.Distance( startPos, endPos );
transform.eulerAngles = new Vector3(0f, 0f, angleToTurn);
}
}
}
}
}

No Script Errors - Character doesnt jump - Unity 3d

Currently building a 2D game, and have created a javascript code for the jump for my character 'Ezio' but it does not do anything when i press 'space' for it to jump. There are no errors with the code either.
#pragma strict
var jump :float = 0;
var jumpspeed : float = 15;
var jumptimer :float = 0;
function Start () {
}
function Update () {
if (jump == 1) {
jumptimer = jumptimer +1;
if (jumptimer >= 50) {
jumptimer = 0;
jump = 0;
}
}
}
if (Input.GetKeyDown ("space"))
{
if (jump == 0) {
rigidbody2D.velocity.y = jumpspeed;
jump = 1;
}
}
Any suggestions on what could be the issue?
Try this:
#pragma strict
var jump :float = 0;
var jumpspeed : float = 15;
var jumptimer :float = 0;
function Start () {
}
function Update() {
if (Input.GetKeyDown("space")) {
if (jump == 1) {
jumptimer = jumptimer + 1;
if (jumptimer >= 50) {
jumptimer = 0;
jump = 0;
}
} else {
rigidbody2D.velocity.y = jumpspeed;
jump = 1;
}
}
}