Making measurements on the object - unity3d

I use the objects that I scan with the photogrammetry method exactly in unity. So when I create a cube and expand this cube to the extent that I want to measure, I give an example. The z value gives the value in meters. What I want to do is to measure the distance with an object to be created between the two points I click on the object and the value I will get over it. How can I make this happen?
I've tried the code below but nothing draws.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class olcumYap : MonoBehaviour
{
private LineRenderer lineRend;
private Vector2 mousePos;
private Vector2 startMousePos;
[SerializeField]
private Text distanceText;
private float distance;
// Start is called before the first frame update
void Start()
{
lineRend = GetComponent<LineRenderer>();
lineRend.positionCount = 2;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
startMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
if (Input.GetMouseButton(0))
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
lineRend.SetPosition(0, new Vector3(startMousePos.x, startMousePos.y, 0f));
lineRend.SetPosition(1, new Vector3(mousePos.x, mousePos.y, 0f));
distance = (mousePos - startMousePos).magnitude;
distanceText.text = distance.ToString("F2") + "metre";
}
}
}

You could try debugging the line positions to see if the problem is the line renderer or the positions.
Debug.Log(<position>);
print(<position>);
It is generally a good practice to log something if it doesnt work to find the issuee.

Related

unity2d move a game object towards a random position

i have a satellite which i let spawn randomly in a different script by just using the method Satellite() and i want it move towards the bottom of the screen but not towards the middle but again a random position of the ground. the problem is that satellitedirection is always 0. also, if i somehow would manage to get the problem solved, wouldn´t every satellite on the screen move towards the same position?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SatelliteBehaviour : MonoBehaviour
{
[SerializeField] Rigidbody2D satelliteRB;
[SerializeField] Transform satelliteFirePoint;
[SerializeField] GameObject satellitePrefab;
float satellitedirection;
void Start()
{
}
void Update()
{
transform.Rotate(0,0,80*Time.deltaTime);
//satelliteRB.velocity = -transform.up * 5;
transform.position = Vector2.MoveTowards(transform.position, new Vector2(satellitedirection, -15), 1 * Time.deltaTime);
Debug.Log(satellitedirection);
}
public void Satellite()
{
Instantiate(satellitePrefab, new Vector2(Random.Range(-18,18),10), Quaternion.identity);
satellitedirection = Random.Range(-18, 18);
}
}
The Instantiate() method returns a game object but it is not assigned to anything. Assign a var and set its position and rotation.
GameObject satelliteObj = Instantiate(satellitePrefab, new Vector2(Random.Range(-18,18),10), Quaternion.identity);
// random rotation
satelliteObj.transform.rotation = Quaternion.Euler(new Vector2(Random.Range(-180, 180), Random.Range(-180, 180)));

Trying to make sliding puzzel game in unity. But the puzzel piece don't move

I am trying to make simple sliding puzzel game in unity. I used https://youtu.be/rJFprTG3wE0 this video as tutorial. In the video block move if clicked but mine doesn't.
using UnityEngine;
public class gamebasic : MonoBehaviour
{
[SerializeField] public Transform empty =null;
private Camera _camera;
// Start is called before the first frame update
void Start()
{
_camera = Camera.main;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
if (hit)
{
if (Vector2.Distance(a: empty.position, b: hit.transform.position) < 1)
{
Vector2 lastemptyposition = empty.position;
empty.position = hit.transform.position;
hit.transform.position = lastemptyposition;
}
}
}
}
}
Here is my code and I am using visual studio 2017 version 15.9.39 and unity 2020.3.11f1.
At the end of the video he makes a comment about changing the value of the distance, if your reference to the empty transform is correct that might be the reason.
You can make this a public variable and test different values, like this:
[SerializeField] private float maxDistanceToEmpty = 2f;
and then you change that line to
if (Vector2.Distance(a: empty.position, b: hit.transform.position) < maxDistanceToEmpty )

Object won fall of the platform in Unity

So i made an ball(player) which moves forward on it's own with script. I want to make that ball act like a normal ball. when it riches the edge of platform it won't fall off. Basicaly it stops on the edge. Here's my image:
Here's my controller script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwerveInputSystem : MonoBehaviour
{
private float _lastFrameFingerPositionX;
private float _moveFactorX;
public float MoveFactorX => _moveFactorX;
void Start(){
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
_lastFrameFingerPositionX = Input.mousePosition.x;
}
else if (Input.GetMouseButton(0))
{
_moveFactorX = Input.mousePosition.x - _lastFrameFingerPositionX;
_lastFrameFingerPositionX = Input.mousePosition.x;
}
else if (Input.GetMouseButtonUp(0))
{
_moveFactorX = 0f;
}
}
}
This is Second script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour{
private SwerveInputSystem _swerveInputSystem;
[SerializeField] private float swerveSpeed = 5f;
[SerializeField] private float maxSwerveAmount = 1f;
[SerializeField] private float verticalSpeed;
void Start(){
_swerveInputSystem = GetComponent<SwerveInputSystem>();
}
void Update(){
float swerveAmount = Time.deltaTime * swerveSpeed * _swerveInputSystem.MoveFactorX;
swerveAmount = Mathf.Clamp(swerveAmount, -maxSwerveAmount, maxSwerveAmount);
transform.Translate(swerveAmount, 0, 0);
float verticalDelta = verticalSpeed * Time.deltaTime;
transform.Translate(swerveAmount, verticalDelta, 0.1f);
}
}
EDITED: Adjusted the answer since we now have some source code.
You are positioning the player directly (using its transform) which will mess up the physics. The purpose of a rigidbody is to let Unity calculate forces, gravity, and so on for you. When you are using physics, and you want to move an object you have three main options:
Teleporting the object to a new position, ignoring colliders and forces like gravity. In this case use the rigidbody's position property.
_ourRigidbody.position = new Vector3(x, y, z);
Moving the object to the new position, similar to teleporting but the movement can be interrupted by other colliders. So, if there is a wall between the object and the new position, the movement will be halted at the wall. Use MovePosition().
_ourRigidbody.MovePosition(new Vector3(x, y, z));
Adding some force to the object and letting the physics engine calculate how the object is moved. There are several options like AddForce() and AddExplostionForce(), etc... see the Rigidbody component for more information.
_ourRigidbody.AddRelativeForce(new Vector3(x, y, z));
In your case you can simply remove the transsform.Translate() calls and instead add some force like this:
//transform.Translate(swerveAmount, 0, 0);
//transform.Translate(swerveAmount, verticalDelta, 0.1f);
Vector3 force = new Vector3(swerveAmount, verticalDelta, 0);
_ourRigidbody.AddForce(force);
We can get the _ourRigidbody variable in the Awake() or Start() method as normal. As you can see I like the Assert checks just to be safe, one day someone will remove the rigidbody by mistake, and then it is good to know about it...
private SwerveInputSystem _swerveInputSystem;
private Rigidbody _ourRigidbody;
void Start()
{
_swerveInputSystem = GetComponent<SwerveInputSystem>();
Assert.IsNotNull(_swerveInputSystem);
_ourRigidbody = GetComponent<Rigidbody>();
Assert.IsNotNull(_ourRigidbody);
}
One likely reason your Rigidbody is not being affected by gravity is due to having the field isKinematic checked to on. From the Rigidbody docs, when toggling on isKinematic,
Forces, collisions or joints will not affect the rigidbody anymore.
The rigidbody will be under full control of animation or script
control by changing transform.position
As gravity is a force and no forces act on the object when this setting is checked, your object will not fall when it is no longer on the platform. A simple solution is to uncheck this box.

Struggling to get my animations to work on my first game

I am trying to make my first game and have been struggling to get my animations to work.
I have been following along with a YouTube course and when it came to coding the animations on Unity i cannot seem to get it to work.
Please can someone who understands coding and Unity have a look at the following screenshots and help me out.
This is my code for my game:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;
private Vector3 input;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Verical"));
Rigidbody.AddForce(input * moveSpeed);
}
}
I cannot get the white dot next to my Player Control script to light up and it will not work.
Any help is appreciated, thanks.
If you are able to change the script, then this is how I would do it:
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
float speed = 10f;
float x = Input.GetAxis(“Horizontal”) * speed * Time.deltaTime;
float z = Input.GetAxis(“Vertical”) * speed * Time.deltaTime;
rb.AddForce(x, 0f, z);
}
And freeze rotation along the x and a axis to not fall over. You can do this in the rigidbody component.

Unity - How to calculate new position for an object from pitch of another object in 3D

I would like to calculate a new position based on the pitch of a mesh in order to make an object following the top of my object which is rotated:
And result in:
I cannot make the square object as represented above as a child (in the Unity object hierarchy) of the line object because the rotated object can see its scale changed at anytime.
Does a mathematics solution can be used in this case?
Hotspots
If you'd like to place something at a particular location on a generic object which can be scaled or transformed anywhere, then a "hotspot" can be particularly useful.
What's a hotspot?
Edit the target gameobject (the line in this case) and add an empty gameobject to it. Give it some appropriate name - "cross arms hotspot" for example, and then move it to the location where you'd like your other gameobject to target. Essentially, a hotspot is just an empty gameobject - a placement marker of sorts.
How do I use it?
All you need is a reference to the hotspot gameobject. You could do this by adding a little script to the pole gameobject which tracks it for you:
public class PowerPole : MonoBehaviour {
public GameObject CrossArmsHotspot; // Set this in the inspector
}
Then you can get that hotspot reference from any power pole instance like this:
var targetHotspot = aPowerPoleGameObject.GetComponent<PowerPole>().CrossArmsHotspot;
Then it's just a case of getting your target object to place itself where that hotspot is, using whichever technique you prefer. If you want it to just "stick" there, then:
void Start(){
targetHotspot = aPowerPoleGameObject.GetComponent<PowerPole>().CrossArmsHotspot;
}
void Update(){
transform.position = targetHotspot.transform.position;
}
would be a (simplfied) example.
A more advanced example using lerp to move towards the hotspot:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CrossArmsMover : MonoBehaviour
{
public GameObject PowerPole;
private GameObject targetHotspot;
public GameObject CrossArms;
public float TimeToTake = 5f;
private float timeSoFar;
private Vector3 startPosition;
private Quaternion startRotation;
// Start is called before the first frame update
void Start()
{
startPosition = CrossArms.transform.position;
startRotation = CrossArms.transform.rotation;
targetHotspot = PowerPole.GetComponent<PowerPole>().CrossArmsHotspot;
}
// Update is called once per frame
void Update()
{
timeSoFar+=Time.deltaTime;
var progress = timeSoFar/TimeToTake;
// Clamp it so it doesn't go above 1.
if(progress > 1f){
progress = 1f;
}
// Target position / rotation is..
var targetPosition = targetHotspot.transform.position;
var targetRotation = targetHotspot.transform.rotation;
// Lerp towards that target transform:
CrossArms.transform.position = Vector3.Lerp(startPosition, targetPosition, progress);
CrossArms.transform.rotation = Quaternion.Lerp(startRotation, targetRotation, progress);
}
}
You would need to put a script on the following gameobject in wich you would put :
GameObject pitcher = //reference to the gameobject with the pitch;
const int DISTANCE_ON_LINE = //distance between the 2 objects
void Update() {
transform.position = pitcher.transform.position + pitcher.transform.forward * DISTANCE_ON_LINE;
}