Making a sprite move - unity3d

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnitMove : MonoBehaviour
{
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 MousePos = Input.mousePosition;
GetComponent<Transform>().position = (MousePos);
}
}
}
What is above is my code and every time I build and run the game the sprite will not go to the position of my mouse clicks but instead just disappears.

Input.mousePosition provides a screen coordinate. This ranges from (0,0) to (Screen.width, Screen.height). The Transform component uses world coordinates. Try looking at its position value after clicking the sprite and see if the X and Y values look like pixel counts.
Use Camera.ScreenToWorldPoint() to transform screen coordinates into world space.

Related

Unity3D: Raycaster.Raycast on UI, get Worldposition of the hit point

I am in UNity3D. I am trying to raycast on UI Element and get the world position of the hit. I have the small test code here. It gives me the name of the target UI Element, but not the position. The world position of the hit is always (0,0,0). Please, can someone suggest, how i can get it right? thank you a lot.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class RaycasterRayScriptTest : MonoBehaviour
{
[SerializeField] private GraphicRaycaster m_Raycaster;
private PointerEventData m_PointerEventData;
private EventSystem m_EventSystem;
[SerializeField] private Vector3 HitPosition;
// Update is called once per frame
void Update()
{
m_PointerEventData = new PointerEventData(m_EventSystem);
m_PointerEventData.position = Input.mousePosition;
List<RaycastResult> results = new List<RaycastResult>();
m_Raycaster.Raycast(m_PointerEventData, results);
foreach (RaycastResult result in results)
{
Debug.Log("Hit " + result.gameObject.name);
HitPosition = result.worldPosition;
Debug.Log("HitPosition " + HitPosition.ToString());
}
}
}
I just solved this problem. You have to set Canvas Render Mode: Screen Space - Camera. Select the camera, that you have to use for the UI. With this UI-Plane will appear as an GameObject in the world. But the ui-plane position is not adjustable, so you have to move the camera back and adjust the field of view of the camera.
And because the UI-Plane is now an Object, the code
HitPosition = result.worldPosition;
works now.
without the changes on the canvas and camera, the code doesn't work, because plane of ui is virtual and it's position set to the camera position. So if you try to get the worldPosition, it uses the distance betwenn camera and UI-Plane, and since it is zero, you will get zero for the worldPosition as well.

Rotate an object around a point in unity

I'm new to Unity. So just for an experiment, I want to create a canon by attaching a rectangle to a circle and when the up arrow key is pressed, the canon change firing angle. So I have a rectangle object that is a sub object of a circle. And then I created a script in C# for the circle object.
Here is the codes that I have:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private float rotation = 0f;
private float timeValue = 0.0f;
public GameObject wheele;
private float xMin = -1.0f, xMax = 1.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.UpArrow))
{
if (rotation >= -90)
transform.Rotate(new Vector3(0.0f, 0.0f, rotation));
rotation -= 2;
Mathf.Clamp(rotation, -90.0f, 0);
}
if(Input.GetKeyDown(KeyCode.DownArrow))
{
if (rotation >= -90)
transform.RotateAround(wheele.transform.position, Vector3.up,20);
rotation += 2;
Mathf.Clamp(rotation, -90.0f, 0);
}
}
}
I tried both transform. Rotate method, but it rotate around the center of the rectangle. But we need the rectangle to rotate with the axis, the center of the circle.
You're asking how to get the pivot point changed, right? Make an empty game object and drag the cannon under it to make it a child, then drag the cannon to a point which you think is fine and rotate the empty game object instead of the cannon, which pretty much just changes the pivot point
There are two main ways.
Update your model to set the pivot point exactly where you want it to rotate. This is how you would do this using blender. This would require you to actually create a model for the canon though (even if it's as simple as the one you've used Unity primitives for)
Create a parent GameObject, and rotate it instead. You can offset the cannon inside this GameObject, to compensate for the pivot point set on the model.

Unity why does my object rotate exactly the same around the y axis in both Space.Self and Space.World?

So I was told that Space.Self rotates around local coordinates and Space.World around global coordinates. So I created a small little project and script in unity to verify. However, they both seem to rotating the same way. Is there something I'm doing wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spin : MonoBehaviour {
public bool isSpinOnSelf = true;
public bool isSpinOnWorld = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(isSpinOnSelf)
transform.Rotate(0,3f,0, Space.Self);
if(isSpinOnWorld)
transform.Rotate(0, 3f, 0, Space.World);
}
}
It is because the object's Y axis is still aligned with the world's Y axis.
You're spinning around the same axis. If you rotated the object so that its Y axis was horizontal, you would notice a difference between the two. In local space the object would appear to "roll" whereas in world space it would still rotate "sideways".

GameObject position changes after I press the play button on Unity

The game has the following scenario:
The other objects have been disabled only to demonstrate the problem. I think to deactivate them do not influence the game, right?
This is what happens when I click play in Unity:
Note that the Ground and Ground_2 objects were moved to the position (0,0) and yes, the sprite pivot is BottomLeft, so it is not centered.
Game settings:
Background
Camera
Camera Script
using UnityEngine;
using System.Collections;
public class CameraSettings : MonoBehaviour {
private float targetRatio = 9f/16f;
// Use this for initialization
void Start () {
Camera cam = GetComponent<Camera>();
cam.aspect = targetRatio;
}
}
Ground (Ground, Ground_2 and Ground_3)
Ground Sprite (Within the GameObject "Ground" there is a sprite)
What is wrong?
You are using Rect Transform for your ground objects. Rect Transform is part of the UI system and should be used for objects inside a Canvas. Just use the standard Transform for your ground objects.

Unity 3D realistic accelerometer control

How do we achieve a control similar to this game?
https://play.google.com/store/apps/details?id=com.fridgecat.android.atiltlite&hl=en
You can do this with builtin physics:
create a level from some simple scaled cubes (don't forget the ground).
add the ball - a sphere, then and add a RigidBody to it. Set a constraint on the rigidbody - check freeze position y (or it will be able to jump out of the level if you put the device upside down).
add this script anywhere on the scene (for example to the camera):
using UnityEngine;
public class GravityFromAccelerometer : MonoBehaviour {
// gravity constant
public float g=9.8f;
void Update() {
// normalize axis
Physics.gravity=new Vector3(
Input.acceleration.x,
Input.acceleration.z,
Input.acceleration.y
)*g;
}
}
or if you want the physics to just affect this one object, add this script to the object and turn off it's rigidbody's affected by gravity:
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class ForceFromAccelerometer : MonoBehaviour {
// gravity constant
public float g=9.8f;
void FixedUpdate() {
// normalize axis
var gravity = new Vector3 (
Input.acceleration.x,
Input.acceleration.z,
Input.acceleration.y
) * g;
GetComponent<Rigidbody>().AddForce (gravity, ForceMode.Acceleration);
}
}
And now you have working ball physics. To make the ball behave as you'd like, try to play with the rigidbody properties. For example, change the drag to something like 0.1.