Line renderer not working as expected? - c#

I am using line renderer to create fruit ninja style swipe effect. But it is not working.Line was supposed to follow the mouse pos but it is not doing so Here is the code. Please help me to solve this. And this script is attached to gameobject line(empty) at position of (0,0,1).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LineFOllow : MonoBehaviour {
int vertexcount =0;
bool mousedown = false;
private LineRenderer line;
void Start () {
line = GetComponent<LineRenderer>();
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) // gets called when mouse is clicked
{
mousedown = true;
}
if (mousedown)
{
Debug.Log("called");
line.positionCount = vertexcount+1;
Vector3 mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
line.SetPosition(vertexcount, mousepos);
vertexcount++;
}
if (Input.GetMouseButtonUp(0))// gets called when mouse is released
{
vertexcount = 0;
line.positionCount = 0;
mousedown = false;
}
}
}

Enable worldspace coordinates for linerender.

In your case I think is better to use a TrailRenderer.
private TrailRenderer trail;
public float depth;
void Start()
{
depth = 10;
trail = GetComponent<TrailRenderer>();
}
void Update()
{
if (Input.GetMouseButton(0))
{
Vector3 mousepos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, depth);
Vector3 position = Camera.main.ScreenToWorldPoint(mousepos);
trail.transform.position = position;
}
}
Change the Time, MinVertexDistance (and other) properties on your TrailRenderer component to get the desired effect.

Related

When enabling the OrbitCam script it's changing the camera view and position how can I enable the it but keep the camera view and position?

The game start when the camera is at this position :
Then the camera move smooth slowly to this position :
Using this script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayingInGameScenesController : MonoBehaviour
{
public GameObject camera;
public LockController lockController;
public GameObject uiTextsImage;
public float transitionSpeed = 5f;
public Transform currentView;
// The initial offset from the target.
private Vector3 offset;
private bool newGame = true;
private bool playingScene = true;
private Vector3 newPos;
private void Start()
{
currentView.position = new Vector3(43.4f, 1f,-6f);
offset = camera.transform.position - currentView.position;
}
public void PlayingSceneInGame()
{
PlayingSceneStatesControls(true);
StartCoroutine(ScenePlayingTime());
}
private void Update()
{
if (SceneManager.GetActiveScene().name != "Main Menu" && newGame == true)
{
PlayingSceneInGame();
newGame = false;
}
}
private void LateUpdate()
{
if (playingScene == false)
{
//Lerp position
camera.transform.position = Vector3.Lerp(camera.transform.position, currentView.position, Time.deltaTime * transitionSpeed);
}
}
private void PlayingSceneStatesControls(bool LockState)
{
lockController.LockControl(LockState);
if (LockState == true)
{
uiTextsImage.SetActive(true);
}
else
{
uiTextsImage.SetActive(false);
playingScene = false;
}
}
IEnumerator ScenePlayingTime()
{
yield return new WaitForSeconds(10);
PlayingSceneStatesControls(false);
}
}
Now at this point I want to check and know when the camera is not moving anymore in the LateUpdate and then when the camera stopped moving to enable true the OrbitCam script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrbitCam : MonoBehaviour
{
//All the variables used in this class(Look below to see what they do. :D )
private const float Y_ANGLE_MIN = 0.0f;
private const float Y_ANGLE_MAX = 50.0f;
private const float DISTANCE_MAX = 10.0f;
private const float DISTANCE_MIN = 0.1f;
private const float TRANS_MIN = 1.0f;
private const float TRANS_MAX = 2.0f;
public Transform lookAt;
public Transform camTransform;
public GameObject player;
private Camera cam;
public float distance = 5.0f;
private float currentX = 0.0f;
private float currentY = 0.0f;
private float sensitivityX = 4.0f;
private float sensitivityY = 1.0f;
private float trandis;
public Vector3 height = new Vector3(0, 0, 0);
private bool below = false;
private List<Renderer> playerRenderers = new List<Renderer>();
private void Start()
{
//Makes camTransform a transform. :)
camTransform = transform;
//Sets variable cam value to the main camera
cam = Camera.main;
foreach (Transform child in player.transform)
{
if (child.GetComponent<Renderer>() != null)
{
playerRenderers.Add(child.GetComponent<Renderer>());
}
}
}
private void Update()
{
//Makes the camera move by looking at the axis of the mouse(Also multiplied by the seisitivity.)
currentX += Input.GetAxis("Mouse X") * sensitivityX;
currentY += Input.GetAxis("Mouse Y") * sensitivityY;
//Limits the Y variable
currentY = Mathf.Clamp(currentY, Y_ANGLE_MIN, Y_ANGLE_MAX);
//Thiago Laranja's scrollwheel implemetation.
if (Input.GetAxis("Mouse ScrollWheel") > 0) { distance += 0.2f; }
if (Input.GetAxis("Mouse ScrollWheel") < 0) { distance -= 0.2f; }
//Makes sure that these variables never go over the max and be les than the min. :)
distance = Mathf.Clamp(distance, DISTANCE_MIN, DISTANCE_MAX);
trandis = Mathf.Clamp(distance, TRANS_MIN, TRANS_MAX) - 1;
for (int i = 0; i < playerRenderers.Count; i++)
{
//Sets players transparency(Make sure that player materials rendering mode has set to transparent or other mode that supports transparency).
playerRenderers[i].material.color = new Color(playerRenderers[i].material.color.r, playerRenderers[i].material.color.g, playerRenderers[i].material.color.b, trandis);
//Disables the object from rendering if your're at distance 0.8.
if (distance <= 0.8f) { playerRenderers[i].enabled = false; }
if (distance > 0.8f) { playerRenderers[i].enabled = true; }
}
//If close enough to the character sinp into distance of 0.1(If distance is 0 the camera cant be rotated.)
if (distance <= 0.8f && below == false) { distance = 0.1f; below = true; }
if (distance >= 0.8f && below == true) { below = false; }
}
private void LateUpdate()
{
//Subtracts hte distance from Z coordinate
Vector3 dir = new Vector3(0, 0, -distance);
//Creates an quaternion for rotation(too bad that we cannot use Vector3. :D )
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
//Sets the cameras position and makes it look at player.
camTransform.position = lookAt.position + height + rotation * dir;
camTransform.LookAt(lookAt.position + height);
}
}
I don'y know how to check when the camera finished/stopped moving to the target position ?
When I'm enabling the OrbitCam for now I'm doing it manual checking the enable box in the editor the OrbitCam change the camera view and position and I want that when I'm enabling the OrbitCam script that it will keep the view and position of the camera in the second screenshot. Not to keep that view and position all the time only for starting the gameplay part. but what I'm getting when enabling the OrbitCam script is :
I'd strongly recommend to use a animation on the camera. This has the big advantage that you can change the camera position like you do in the script and you have the option to set animation events. So you can call a function at the end of the animation. So if the camera animation is over, the camera is now in the correct position, you can enable the orbit cam. It is also very simple to set up! Hope that helps you!

LineRender | collision himself with raycast2D

i build game with line that you can control his movement.
every few seconeds the line create hole for the player can move through them.
look picture:
enter image description here
now in my code you can see the playerMovement, createLine and drawLine.
i draw the line By player location and every few seconeds i stop draw to millie seconed to create hole and than draw new line.
my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DrawLineNisayon : MonoBehaviour
{
[SerializeField] private GameObject linePrefab;
LineRenderer lineRenderer;
public GameObject currentLine;
private bool createHole = false;
private bool drawLine = false;
float rotZ = 0f;
public float speedMovement = 3f;
public float speedRotation = 6f;
public float timingCreateHoles = 2f;
public float widthHoles = 0.2f;
public EdgeCollider2D edgeCollider2D;
public List<Vector2> posLine;
void Start()
{
CreateLine();
}
void Update()
{
PlayerMovement(speedMovement);
DrawLine();
}
private void CreateLine()
{
currentLine = Instantiate(linePrefab, Vector3.zero, Quaternion.identity);
lineRenderer = currentLine.GetComponent<LineRenderer>();
edgeCollider2D = currentLine.GetComponent<EdgeCollider2D>();
posLine.Clear();
posLine.Add(transform.position);
posLine.Add(transform.position);
lineRenderer.SetPosition(0, posLine[0]);
lineRenderer.SetPosition(1, posLine[1]);
edgeCollider2D.points = posLine.ToArray();
}
private void DrawLine()
{
if(!drawLine)
{
posLine.Add(transform.position);
lineRenderer.positionCount++;
lineRenderer.SetPosition(lineRenderer.positionCount - 1, transform.position);
edgeCollider2D.points = posLine.ToArray();
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, 1f);
Debug.DrawRay(posLine[lineRenderer.positionCount - 1], transform.right);
if(createHole == false){
StartCoroutine(DrawHole(timingCreateHoles));
createHole = true;
}
}
}
private IEnumerator DrawHole(float timingCreateHoles)
{
yield return new WaitForSeconds(timingCreateHoles);
drawLine = true;
StartCoroutine(DrawLine(widthHoles));
}
private IEnumerator DrawLine(float widthHoles)
{
yield return new WaitForSeconds(widthHoles);
CreateLine();
drawLine = false;
createHole = false;
}
private void PlayerMovement(float speed)
{
transform.Translate(Vector3.right * speed * Time.deltaTime);
if(Input.GetKey(KeyCode.D) && !Input.GetKey(KeyCode.A))
{
transform.Rotate(0f, 0f, rotZ);
rotZ = speedRotation;
}
if (!Input.GetKey(KeyCode.D) && Input.GetKey(KeyCode.A))
{
transform.Rotate(0f, 0f, rotZ);
rotZ = -speedRotation;
}
}
}
so what is my problem? i try to create raycast to check collision with the line himself like the game "snake". i tryed to create raycast in function "DrawLine" and i havnt idea how to do that.
my line built by list of vector2 like you can see in my code, its say that i need to compare vector to vector and i dont know how...
*i try collision with the last index in line, not with the circle in the picture.

UI image is instantiating in wrong position

Im trying to instansiate a line where i click in the screen, the origin of the line is where i first clicked and the end of the line is where the mouse is at the moment all this happens while the mouse button is down. The problem is that i give give the origin of the line the exact same value of the mouse in that moment but is been instansiated with a offset and i dont understand why because im doing some prints of the transform.position of the line origin and of the mouse and both match.
The script is in the panel and he es contained by the canvas, the canvas Render mode is World Space.
Heres an Screenshoot where it shows exactly where i click and where it instansiates.
CODE:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementController : MonoBehaviour
{
public float mousePos;
public Camera cam;
public GameObject dirLine;
public Vector2 origin;
GameObject tempLine;
Vector2 ending;
Vector2 dir;
float width;
bool spawned;
// Start is called before the first frame update
void Start()
{
cam = GameObject.Find("Main Camera").GetComponent<Camera>();
spawned = false;
}
// Update is called once per frame
void Update()
{
//Debug.Log(Input.mousePosition);
if (tempLine != null)
{
ending = Input.mousePosition;
dir = ending - origin;
width = dir.magnitude;
//tempLine.GetComponent<RectTransform>().localPosition = origin;
tempLine.GetComponent<RectTransform>().sizeDelta = new Vector2(width, tempLine.GetComponent<RectTransform>().sizeDelta.y);
float angle = Vector2.SignedAngle(dir, Vector2.up);
tempLine.transform.eulerAngles = new Vector3(0, 0, -(angle - 90));
Debug.Log("LocalPosition de la linea:"+tempLine.GetComponent<RectTransform>().localPosition);
}
}
private void OnMouseDown()
{
spawned = true;
Vector3 screenpoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f);
//origin = GameObject.Find("Panel").transform.localPosition;
tempLine = Instantiate(dirLine,transform);
origin = screenpoint;
tempLine.transform.localPosition = origin;
tempLine.GetComponent<RectTransform>().localPosition = origin;
Debug.Log("Posicion del Mouse al ser clicado"+Input.mousePosition);
}
private void OnMouseUp()
{
spawned = false;
Destroy(tempLine);
}
}

How do i set the velocity of a sprite to the opposite direction of the mouse pointer at a certain speed?

/*I am making a 2d game in Unity that works similarly to billiards, but with other aspects. When the player holds down button 0, a line drags away from the ball to show the direction and speed the ball will be hit off in. I don't know how to set that velocity or how to add a force like that.
I've tried setting the velocity directly, then adding fake frictions, but that didn't work too well. I also tried adding a force to the ball, and also making an empty game object that follows the pointer with a point effecter to repel the ball. But I cant seem to get anything to work.
--Also I apologize for the messy code, i'm still kinda new to this
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LineDrawer : MonoBehaviour
{
public Transform tr; //this is the transform and rigid body 2d of the
ball
public Rigidbody2D rb;
public LineRenderer line; // the line rendered is on the ball
public float hitForce = 10;
// Start is called before the first frame update
void Start()
{
line = GetComponent<LineRenderer>();
line.SetColors(Color.black, Color.white);
}
// Update is called once per frame
void FixedUpdate()
{
line.SetPosition(0, tr.position - new Vector3(0, 0, 0));
if (Input.GetMouseButton(0)&&PlayerPrefs.GetInt("Moving")==0)
{
line.SetWidth(.25f, .25f);
line.SetPosition(1, Camera.main.ScreenToWorldPoint(Input.mousePosition));
float len = Vector2.Distance(line.GetPosition(0), line.GetPosition(1)); //this is for determining the power of the hit
}
else
{
line.SetWidth(0, 0); //make the line invisible
}
if (Input.GetMouseButtonUp(0) && (PlayerPrefs.GetInt("Moving")==0))
{
Vector2.Distance(Input.mousePosition, tr.position)*100;
Debug.Log("Up");
rb.velocity = //this is what i cant work out
PlayerPrefs.SetInt("Moving", 1);
}
}
}
//5 lines from the bottom is where i'm setting the velocity.
Just rewrite your script to the following:
using UnityEngine;
public class Ball : MonoBehaviour
{
private LineRenderer line;
private Rigidbody2D rb;
void Start()
{
line = GetComponent<LineRenderer>();
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
line.SetPosition(0, transform.position);
if (Input.GetMouseButton(0))
{
line.startWidth = .05f;
line.endWidth = .05f;
line.SetPosition(1, Camera.main.ScreenToWorldPoint(Input.mousePosition));
}
else
{
line.startWidth = 0;
line.endWidth = 0;
}
if (Input.GetMouseButtonUp(0))
{
Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
direction.Normalize();
rb.AddForce(direction * 3f, ForceMode2D.Impulse);
}
}
}

How to bringback an object to its original position after rotation in unity?

I have created a project where a cube is rotated when we touch on it. I want the cube to return back to its original position when the user stops touching the cube. Below I have added the source code of rotating a cube:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshRenderer))]
public class dr : MonoBehaviour
{
#region ROTATE
private float _sensitivity = 1f;
private Vector3 _mouseReference;
private Vector3 _mouseOffset;
private Vector3 _rotation = Vector3.zero;
private bool _isRotating;
#endregion
void Update()
{
if(_isRotating)
{
// offset
_mouseOffset = (Input.mousePosition - _mouseReference); // apply rotation
_rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity; // rotate
gameObject.transform.Rotate(_rotation); // store new mouse position
_mouseReference = Input.mousePosition;
}
}
void OnMouseDown()
{
// rotating flag
_isRotating = true;
// store mouse position
_mouseReference = Input.mousePosition;
}
void OnMouseUp()
{
// rotating flag
_isRotating = false;
}
}
edited code:-
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshRenderer))]
public class pt : MonoBehaviour
{
#region ROTATE
private float _sensitivity = 1f;
private Vector3 _mouseReference;
private Vector3 _mouseOffset;
private Vector3 _rotation = Vector3.zero;
private bool _isRotating;
private Quaternion original;
#endregion
void start(){
original = transform.rotation;
}
void Update()
{
if(_isRotating)
{
// offset
_mouseOffset = (Input.mousePosition - _mouseReference); // apply rotation
_rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity; // rotate
gameObject.transform.Rotate(_rotation); // store new mouse position
_mouseReference = Input.mousePosition;
}
}
public void OnMouseDown()
{
// rotating flag
_isRotating = true;
// store mouse position
_mouseReference = Input.mousePosition;
}
public void OnMouseUp()
{
// rotating flag
_isRotating = false;
transform.rotation = original;
}
}
"im trying to rotate a 3d model of a sofa and return to its starting rotation.but if i used this code " whenever if i stopped touching the sofa , it turns to **backside of sofa"**
i want it to return to initial rotation.u can see initally this is how the sofa looks like and if i stopped touching it returns to its backside of sofa. i want it to return to its front side again if i stopped rotation
I want the cube to return back to its original position when the user
stopped touching the cube
I can't exactly tell which part of this you are struggling with but you can simply get the position of the GameObject in the Start or Awake function then set the transform.position to that value when OnMouseUp is called.
private Vector3 originalPos;
void Start()
{
//Get the original position
originalPos = transform.position;
}
void OnMouseUp()
{
_isRotating = false;
//Reset GameObject to the original position
transform.position = originalPos;
}
EDIT:
For rotation, it is also the-same thing. Just use Quaternion and transform.rotation instead of Vector3 and transform.position.
private Quaternion originalPos;
void Start()
{
//Get the original rotation
originalPos = transform.rotation;
}
void OnMouseUp()
{
_isRotating = false;
//Reset GameObject to the original rotation
transform.rotation = originalPos;
}
You still have to incorporate that into the original code from your answer. If this is something you can't do then consider watching Unity's scripting tutorial here.

Categories