UI image is instantiating in wrong position - c#

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);
}
}

Related

Unity3d How to make line start from mouse position on camera

Currently, the line starts where I click and locks to those coordinates.
However, I want the line to start where I click on the screen and not start moving until I let go of the mouse.
(Game currently has a ball falling).
using UnityEngine;
using System.Collections;
public class TrailCollider : MonoBehaviour
{
private LineRenderer line; // Reference to LineRenderer
private Vector3 mousePos;
public PhysicsMaterial2D phys;
private Vector3 startPos; // Start position of line
private Vector3 endPos; // End position of line
void Update ()
{
// On mouse down new line will be created
if(Input.GetMouseButtonDown(0))
{
if(line == null)
createLine();
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
line.SetPosition(0,mousePos);
line.SetPosition(1,mousePos);
startPos = mousePos;
}
else if(Input.GetMouseButtonUp(0))
{
if(line)
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
line.SetPosition(1,mousePos);
endPos = mousePos;
addColliderToLine();
line = null;
}
}
else if(Input.GetMouseButton(0))
{
if(line)
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
line.SetPosition(1,mousePos);
}
}
}
// Following method creates line runtime using Line Renderer component
private void createLine()
{
line = new GameObject("Line").AddComponent<LineRenderer>();
line.material = new Material(Shader.Find("Diffuse"));
line.SetVertexCount(2);
line.SetWidth(0.1f,0.1f);
line.SetColors(Color.black, Color.black);
line.useWorldSpace = true;
}
// Following method adds collider to created line
private void addColliderToLine()
{
BoxCollider2D col = new GameObject("Collider").AddComponent<BoxCollider2D> ();
col.transform.parent = line.transform; // Collider is added as child object of line
col.sharedMaterial = phys;
float lineLength = Vector3.Distance (startPos, endPos); // length of line
col.size = new Vector3 (lineLength, 0.1f, 1f); // size of collider is set where X is length of line, Y is width of line, Z will be set as per requirement
Vector3 midPoint = (startPos + endPos)/2;
col.transform.position = midPoint; // setting position of collider object
// Following lines calculate the angle between startPos and endPos
float angle = (Mathf.Abs (startPos.y - endPos.y) / Mathf.Abs (startPos.x - endPos.x));
if((startPos.y<endPos.y && startPos.x>endPos.x) || (endPos.y<startPos.y && endPos.x>startPos.x))
{
angle*=-1;
}
angle = Mathf.Rad2Deg * Mathf.Atan (angle);
col.transform.Rotate (0, 0, angle);
}
}

Line renderer not working as expected?

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.

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.

Move the camera only until a certain position

https://scontent.fmgf1-2.fna.fbcdn.net/v/t34.0-12/15870843_1543174992374352_1359602831_n.gif?oh=dc048c9e04617007c5e82379fd5a9c1a&oe=586CC623
Can you see the blue area in this gif? I want block the camera when the player go more to left, to not see the blue area. This is the code that I'm using to move the camera:
public class configuracoesDaCamera : MonoBehaviour {
Vector3 hit_position = Vector3.zero;
Vector3 current_position = Vector3.zero;
Vector3 camera_position = Vector3.zero;
float z = 0.0f;
public static bool bDedoNoHud;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
hit_position = Input.mousePosition;
camera_position = transform.position;
}
if (Input.GetMouseButton(0))
{
current_position = Input.mousePosition;
LeftMouseDrag();
}
Debug.Log("bDedoNoHud" + bDedoNoHud);
}
void LeftMouseDrag()
{
if (!bDedoNoHud)
{
// From the Unity3D docs: "The z position is in world units from the camera." In my case I'm using the y-axis as height
// with my camera facing back down the y-axis. You can ignore this when the camera is orthograhic.
current_position.z = hit_position.z = camera_position.y;
// Get direction of movement. (Note: Don't normalize, the magnitude of change is going to be Vector3.Distance(current_position-hit_position)
// anyways.
Vector3 direction = Camera.main.ScreenToWorldPoint(current_position) - Camera.main.ScreenToWorldPoint(hit_position);
// Invert direction to that terrain appears to move with the mouse.
direction = direction * -1;
Vector3 position = camera_position + direction;
transform.position = position;
}
}
}
You mean setting up boundaries?
This should help you
Put it in the update()

Object doesn't move with mouse pointer

I have a 2d object that drops when I click the mouse button, and the object moves along the x-axis just fine. But it's not moving according to my mouse pointer's x-coordinate, and when I hit the mouse button it does not drop the object at the position where the mouse pointer is located. I want to fix this issue for the object's movement along the x-axis.
Code:
public class Mouse : MonoBehaviour {
Rigidbody2D body;
float mousePosInBlocks;
void Start () {
body = GetComponent<Rigidbody2D> ();
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
body.isKinematic = false;
}
Vector3 ballPos = new Vector3 (0f, this.transform.position.y, 0f);
mousePosInBlocks = Input.mousePosition.x / Screen.width * 4;
//restrict the position not outside
ballPos.x = Mathf.Clamp (mousePosInBlocks, -2.65f, 2.65f);
this.transform.position = ballPos;
}
}
To make object align with the cursor, use camera.ScreenToWorldPoint function instead of dividing mouse position by Screen.width. Simply simply dividing by screen width is incorrect, since screen position may also have offset if game window is not exactly in the screen corner. Some more info here: http://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
Also, just an advice - when using rigidbodies, do not use transform.position, use rigidbody.position instead, it is much more efficient. So the code would look like this:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody2D))]
public class Mouse : MonoBehaviour {
Rigidbody2D body;
float mousePosInBlocks;
void Start () {
body = GetComponent<Rigidbody2D> ();
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
body.isKinematic = false;
}
Vector3 ballPos = new Vector3 (0f, this.transform.position.y, 0f);
mousePosInBlocks = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
//restrict the position not outside
ballPos.x = Mathf.Clamp (mousePosInBlocks, -2.65f, 2.65f);
body.position = ballPos;
}
}

Categories