Unity - how do i move the pencil higher then the mouse - c#

The problem is that the pencil it's way too close to the mousePosition. i want to put the pencil higher than the mousePosition.
here is an image as reference : https://ibb.co/s6v25t9
The thing i want to achieve, it's the pencil to be higher than the line drawn
This is taken from a project. it's not my own code but i am trying to figure out how to fix some bugs and this one i cant really figure out how to fix
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.IO;
public class GameManager : MonoBehaviour
{
[Tooltip("The color of the drawn lines")]
public Color lineColor;
public Material lineMaterial;
public Transform Pencil;
public Sprite SurpriseGlass;
public Sprite HappyGlass;
public Sprite SadGlass;
public Slider PenCapacity;
public Text PenPercent;
[HideInInspector]
public GameObject[] Hint;
public Image Star1;
public Image Star2;
public Image Star3;
public GameObject LevComp;
private GameObject[] Obs;
private List<GameObject> listLine = new List<GameObject>();
public List<Vector2> listPoint = new List<Vector2>();
private GameObject currentLine;
public GameObject currentColliderObject;
private GameObject hintTemp;
private GameObject[] waterTap;
private GameObject Glass;
private Vector3 LastMosPos;
private BoxCollider2D currentBoxCollider2D;
private LineRenderer lines;
private LineRenderer currentLineRenderer;
private bool stopHolding;
private bool allowDrawing = true;
[HideInInspector]
public bool completed;
int clickCont;
private List<Rigidbody2D> listObstacleNonKinematic = new List<Rigidbody2D>();
private GameObject[] obstacles;
float mosDis;
bool canCreate;
RaycastHit2D hit_1;
RaycastHit2D hit_2;
RaycastHit2D hit_3;
GameObject TemLine;
void Start()
{
Pencil.gameObject.SetActive(false);
waterTap = GameObject.FindGameObjectsWithTag("Interactive");
Glass = GameObject.FindGameObjectWithTag("GlassParent");
Glass.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Static;
Hint = GameObject.FindGameObjectsWithTag("Hint");
for (int i = 0; i < Hint.Length; i++)
{
Hint[i].SetActive(false);
}
lineMaterial.SetColor("_Color", lineColor);
Obs = GameObject.FindGameObjectsWithTag("Obstacle");
for (int i = 0; i < Obs.Length; i++)
{
Obs[i].GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Static;
}
}
void Update()
{
if (PenCapacity.value <= 0.01f || !Input.GetMouseButton(0))
{
Pencil.gameObject.SetActive(false);
}
if (Input.GetMouseButtonDown(0))
{
GameObject thisButton = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject; //Get the button on click
if (thisButton != null) //Is click on button
{
allowDrawing = false;
print("cant drwa");
}
else //Not click on button
{
allowDrawing = true;
stopHolding = false;
listPoint.Clear();
CreateLine(Input.mousePosition);
print("draw");
}
}
else if (Input.GetMouseButton(0) && !stopHolding && allowDrawing && PenCapacity.value > 0)
{
RaycastHit2D rayHit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (LastMosPos != Camera.main.ScreenToWorldPoint(Input.mousePosition))
{
if (rayHit.collider == null)
{
Pencil.gameObject.SetActive(true);
Pencil.position = new Vector3(LastMosPos.x, LastMosPos.y, 0);
if (canCreate == false)
{
float dist = Vector3.Distance(LastMosPos, Camera.main.ScreenToWorldPoint(Input.mousePosition));
Pencil.GetComponent<TrignometricRotation>().enabled = true;
PenCapacity.value = PenCapacity.value - dist / 25;
PenPercent.text = Mathf.FloorToInt(PenCapacity.value * 100).ToString() + " %";
if (Mathf.FloorToInt(PenCapacity.value * 100) < 75)
{
Star3.gameObject.SetActive(false);
}
if (Mathf.FloorToInt(PenCapacity.value * 100) < 50)
{
Star2.gameObject.SetActive(false);
}
if (Mathf.FloorToInt(PenCapacity.value * 100) < 25)
{
Star1.gameObject.SetActive(false);
}
}
}
}
else
{
Pencil.GetComponent<TrignometricRotation>().enabled = false;
}
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
float ab = Vector2.Distance(LastMosPos, mousePos);
mosDis = mosDis + ab;
if (!listPoint.Contains(mousePos) && mosDis > .02f)
{
mosDis = 0;
//Add mouse pos, set vertex and position for line renderer
if (canCreate == false)
{
if (rayHit.collider == null)
{
listPoint.Add(mousePos);
}

In the code you posted the value of LastMosPos is never changed so I can't say where you get it from.
However instead of the line
Pencil.position = new Vector3(LastMosPos.x, LastMosPos.y, 0);
you probably could simply add a certain offset like e.g.
Pencil.position = new Vector3(LastMosPos.x, LastMosPos.y + 20f, 0);
to make the pencil appear 20 Unity units (in a Screenspace Overlay canvas this euqals 20 Pixels) above the LastMosPos.

Related

Unity stop object at position after move

I just started learning Unity and C#
I'm trying to move my sprite over a line I draw on-screen with the mouse, it looks like the script is more or less working, but I would like to keep the GameObject at the position it is at the end of the line when it finishes the movement.
As you can see from the picture every time it finishes the animation it goes back to its original position (0,0).
How can I stop this behavior?
using System.Collections;
using System.Collections.Generic;
using Unity.Burst.Intrinsics;
using Unity.VisualScripting;
using UnityEngine;
public class Follow : MonoBehaviour
{
private LineRenderer lineRenderer;
public GameObject objectToMove;
public float speed = 5f;
private Vector3[] positions = new Vector3[397];
private Vector3[] pos;
private int index = 0;
private GameObject toFollow;
DrawLines drawLines;
[SerializeField] GameObject gameController;
private bool isDrawingLineDone = false;
// Start is called before the first frame update
void Awake()
{
drawLines = gameController.GetComponent<DrawLines>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) == true) // caso linea si e click
{
clearLines();
}
if (drawLines.isLinePresent == true && Input.GetMouseButtonUp(0) == true)
{
if (!isDrawingLineDone)
{
pos = GetLinePointsInWorldSpace();
objectToMove.transform.position = pos[index];
isDrawingLineDone = true;
}
}
if (isDrawingLineDone == true && finishMove == false)
{
Move();
}
else if (isDrawingLineDone == true && finishMove == true)
{
objectToMove.transform.position = pos[pos.Length - 1];
}
}
Vector3[] GetLinePointsInWorldSpace()
{
//Get the positions which are shown in the inspector
toFollow = GameObject.Find("Linea");
lineRenderer = toFollow.GetComponent<LineRenderer>();
lineRenderer.GetPositions(positions);
//the points returned are in world space
return positions;
}
// MOve the gameObject
private bool finishMove = false;
void Move()
{
objectToMove.transform.position = Vector3.MoveTowards(objectToMove.transform.position,
pos[index],
speed * Time.deltaTime);
if (objectToMove.transform.position == pos[index])
{
index += 1;
if (objectToMove.transform.position == pos[pos.Length - 1])
{
print("DONE");
finishMove = true;
}
}
if (index == pos.Length)
{
index = 0;
}
}
// delete other line if there is
private GameObject toDestroy;
void clearLines()
{
toDestroy = GameObject.Find("Linea");
Destroy(toDestroy);
drawLines.isLinePresent = false;
}
}

How to utilize stacking blocks under the player object(cylinder) by using rigidbodies in unity3d?

I am working on a hypercasual game project which is very similar to Matching Cubes. Initially, I was using transform to stack blocks under my cylinder(player object). But in the game there will be a ramp to jump through it and by using transform I was ignoring the physics and it passes through the ramp. So I changed it a little bit by utilizing the rigidbody for the cylinder. If there is no block it jumps through the ramp but I need it to jump with blocks. The problem is I couldn't find a way to stack them under the cylinder by using rigidbody. Tried MovePosition or AddForce but it does not work at all.
How can I stack the blocks under the cylinder but also make them jump through the ramp together?
Here is my StackManager.cs . There is a Regulator function that will check the 'picks' list and regulate the positions. It is the function where I handle all positioning.
I also tried making the positioning by transform and when it collides with ramp, stop the Regulator() and AddForce(Vector3.up*offset) but it did not move up a bit.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;
public class StackManager : MonoBehaviour
{
public static StackManager instance;
[SerializeField] private float distanceBetweenObjs;
[SerializeField] private Transform prevObject = null;
[SerializeField] private Transform parent;
[SerializeField] private Transform cylinder;
[SerializeField] private Transform trailer;
private List<Transform> picks; // Use this to order gate and random gate
private Vector3 firstPosition;
private int comboCounter; // fever mode tracker
private Rigidbody rb;
private Transform prev;
private void Awake() {
if(instance == null) {
instance = this;
}
}
void Start()
{
rb = cylinder.gameObject.GetComponent<PlayerController>().rb;
comboCounter = 0;
picks = new List<Transform>();
firstPosition = new Vector3(cylinder.position.x, cylinder.position.y, cylinder.position.z);
}
// Update is called once per frame
void Update()
{
Regulator();
}
void CheckChildren() {
List<Transform> children = new List<Transform>();
foreach (Transform child in picks)
{
children.Add(child);
}
for(int i = 0; i < children.Count - 2; i++) {
if (children[i].isSameMaterial2(children[i+1], children[i+2])) {
comboCounter++;
Destroy(children[i].gameObject);
Destroy(children[i+1].gameObject);
Destroy(children[i+2].gameObject);
picks.Remove(children[i]);
picks.Remove(children[i+1]);
picks.Remove(children[i+2]);
};
}
if(comboCounter == 3) {
SpeedBoost(); //fever mode
comboCounter = 0;
}
}
public void PickUp(GameObject pickedObj){
pickedObj.tag = "Picked";
pickedObj.transform.parent = parent;
picks.Add(pickedObj.transform);
}
private void Regulator(){
//Position of cylinder
//set y value based on the # of children objects
/**
*hold the first position of cylinder
*make calculation by referencing it
*reference + localScale.y + 0.1f:
*/
Vector3 newPos = new Vector3(cylinder.position.x, firstPosition.y, cylinder.position.z);
foreach (Transform child in picks)
{
newPos.y += child.localScale.y + 0.1f;
}
//cylinder.position = newPos;
rb.MovePosition(newPos);
//Position of children
if(picks.Count>0) {
prevObject = picks[picks.Count-1];
}
/**
*For each child
* cylinder-0.1f-pick-0.1f-pick-...
*/
prev = cylinder;
for(int i = 0; i < picks.Count; i++)
{
if(i==0){
picks[i].position = new Vector3(prev.position.x, prev.position.y-1.2f, prev.position.z);
//picks[i].gameObject.GetComponent<Rigidbody>().position(new Vector3(prev.position.x, prev.position.y-1.2f, prev.position.z));
} else {
//picks[i].gameObject.GetComponent<Rigidbody>().MovePosition(new Vector3(prev.position.x, prev.position.y-prev.localScale.y -0.1f, prev.position.z));
picks[i].position = new Vector3(prev.position.x, prev.position.y-prev.localScale.y -0.1f, prev.position.z);
}
prev = picks[i];
}
//Position of trailer object
if(picks.Count>0) {
trailer.position = new Vector3(prev.position.x, prev.position.y-0.2f, prev.position.z); //relocate the trailer object under last pick
trailer.GetComponent<TrailRenderer>().material = prev.GetComponent<MeshRenderer>().material; //change the color of the trail
}
CheckChildren(); //check for the 3-conjugate combo
}
public void ChangeRampState() {
Debug.Log("prev.gameObject");
Debug.Log(prev.gameObject);
prev.gameObject.GetComponent<Collider>().isTrigger = false;
rb.AddForce(Vector3.up * 300);
}
public void OrderPicks() {
picks.Sort((x, y) => string.Compare(x.GetComponent<MeshRenderer>().sharedMaterial.name, y.GetComponent<MeshRenderer>().sharedMaterial.name));
}
public void ShufflePicks() {
picks = picks.Fisher_Yates_CardDeck_Shuffle();
}
async public void onObstacle(Transform pickToDestroy) {
pickToDestroy.gameObject.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePosition;
pickToDestroy.parent = null;
await Task.Delay(200);
picks.Remove(pickToDestroy);
}
public void SpeedBoost() {
cylinder.gameObject.GetComponent<PlayerController>().rb.velocity *= 2;
}
}

How can I move the Main Camera to a new position?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayingInGameScenesController : MonoBehaviour
{
public LockController lockController;
public Vector3 targetPosition;
public GameObject uiTextsImage;
public float cameraMoveSpeed;
private bool newGame = true;
private bool playingScene = true;
public void PlayingSceneInGame()
{
PlayingSceneStatesControls(true);
StartCoroutine(ScenePlayingTime());
}
private void Update()
{
if (SceneManager.GetActiveScene().name != "Main Menu" && newGame == true)
{
PlayingSceneInGame();
newGame = false;
}
if(playingScene == false)
{
// X 40.73769 to -6 Y 1.1 to 1 Z -4.641718 to 43.4
Vector3 camPos = Camera.main.transform.position;
Vector3 newPos = new Vector3(camPos.x)
Camera.main.transform.position = Vector3.Lerp(Camera.main.transform.position, targetPosition, cameraMoveSpeed * Time.deltaTime);
}
}
private void PlayingSceneStatesControls(bool LockState)
{
lockController.LockControl(LockState);
if (LockState == true)
{
// change state of free look camera height and view distance.
// change the cameras states enable true/false.
// change the ui texts for description text and scene text enable true/false.
uiTextsImage.SetActive(true);
}
else
{
uiTextsImage.SetActive(false);
playingScene = false;
}
}
IEnumerator ScenePlayingTime()
{
yield return new WaitForSeconds(10);
PlayingSceneStatesControls(false);
}
}
In the Update :
if(playingScene == false)
{
// X 40.73769 to -6 Y 1.1 to 1 Z -4.641718 to 43.4
Vector3 camPos = Camera.main.transform.position;
Vector3 newPos = new Vector3(camPos.x)
Camera.main.transform.position = Vector3.Lerp(Camera.main.transform.position, targetPosition, cameraMoveSpeed * Time.deltaTime);
}
First should I move the two variables camPos and newPos to the Start ?
Second the values X Y Z the left values is where the camera is position at now and the right values where to should move to smooth slowly. From the current position on X the current position is 40.73769 to -6 same for the Y and Z I just wrote this values to remember but the idea is to move smooth slowly the camera from the current position to the new position : X -6 Y 1 and Z to 43.4
Should I do it in the Update or Late or Fixed Update ?
This is the main camera original position :
And this is the target position I want the main camera to get I entered the new target position values :
What I tried :
In the Start :
private void Start()
{
Vector3 camPos = Camera.main.transform.position;
newPos = new Vector3(camPos.x - 46.73769f, camPos.y - 0.1f, camPos.z + 48.041718f);
}
Then in the Update :
if(playingScene == false)
{
// X 40.73769 - 46.73769 Y 1.1 - 0.1 Z -4.641718 + 48.041718
Camera.main.transform.position = Vector3.Lerp(Camera.main.transform.position, newPos, cameraMoveSpeed * Time.deltaTime);
}
Then I changed the values in the Start switched Z and X :
private void Start()
{
Vector3 camPos = Camera.main.transform.position;
newPos = new Vector3(camPos.x - 48.041718f, camPos.y - 0.1f, camPos.z + 46.73769f);
}
In both cases the main camera start from some other position not the original position at all and ending in other position :
Starting somewhere under/inside the spaceship :
And ending here :
Working :
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)
{
// change state of free look camera height and view distance.
// change the cameras states enable true/false.
// change the ui texts for description text and scene text enable true/false.
uiTextsImage.SetActive(true);
}
else
{
uiTextsImage.SetActive(false);
playingScene = false;
}
}
IEnumerator ScenePlayingTime()
{
yield return new WaitForSeconds(10);
PlayingSceneStatesControls(false);
}
}

Unity what's wrong with my instantiating algorithm?

I dont know if I can call this algorithm. But I am working on a game in which player will move in a circular path.
As you can see in the picture player is suppose to orbit the circle. And obstacle shall be instantiated in the circle.I am trying to first create the obstacle in first half(left to the long cube) and then in the second half. But things are getting created in the next half too when code is not supposed to do that. Also, it is showing argument exception error. Please have a look at my code and tell me whether my method is wrong or my formulas are wrong or anything else.
public class ObjectInstantiater : MonoBehaviour {
DataHolder dataholder;
GameObject Obstacle;
LevelData leveldata;
private int currentlevel=0; // default level starts from 0
private List<GameObject> Inactivegameobject = new List<GameObject>(); // this object can be used
private List<GameObject> Activegameobject = new List<GameObject>();
private int totalgameobjects;
private int firsthalfgameobjects, secondhalfgameobjects;
public float outerradius;
public float innerradius;
private bool shallspawnouterradiues = true;
// Use this for initialization
void Awake () {
dataholder = (Object)GameObject.FindObjectOfType<DataHolder>() as DataHolder;
Obstacle = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
leveldata = dataholder.Leveldata[0];
}
void Start()
{
Updateleveldata();
FirstHalf();
}
public int Currentlevel
{
get { return currentlevel; }
set { currentlevel = value;
leveldata = dataholder.Leveldata[currentlevel];//sets the level data
}
}
private void Updateleveldata() // this function gets called after a round
{
totalgameobjects = Random.Range(leveldata.MinimumObstacle, leveldata.MaximumObstacle);
firsthalfgameobjects = Mathf.RoundToInt(totalgameobjects / 2);
secondhalfgameobjects = totalgameobjects - firsthalfgameobjects;
}
private void FirstHalf()
{
Debug.Log(firsthalfgameobjects);
Vector3 pos;
if (Inactivegameobject.Count < firsthalfgameobjects)
{
for (int x = 0; x <= (firsthalfgameobjects - Inactivegameobject.Count); x++)
{
GameObject obs = Instantiate(Obstacle) as GameObject;
obs.SetActive(false);
Inactivegameobject.Add(obs);
}
}
float spawnangledivision = 180 / firsthalfgameobjects;
float spawnangle = 180f;
for(int x = 0; x < firsthalfgameobjects; x++)
{
float proceduralRandomangle = spawnangle;
proceduralRandomangle = Random.Range(proceduralRandomangle , proceduralRandomangle + 2f);
if (shallspawnouterradiues)
{
pos = new Vector3(outerradius * Mathf.Cos(spawnangle), outerradius * Mathf.Sin(spawnangle), 0f);
shallspawnouterradiues = false;
}else
{
pos = new Vector3(innerradius * Mathf.Cos(spawnangle), innerradius * Mathf.Sin(spawnangle), 0f);
shallspawnouterradiues = true;
}
spawnangle += spawnangledivision;
Inactivegameobject[0].SetActive(true); // set it to 0
Inactivegameobject[0].transform.position = pos;
Activegameobject.Add(Inactivegameobject[0]);
Inactivegameobject.RemoveAt(0);
}
}
private void SecondHalf()// No need to check this
{
if (Inactivegameobject.Count < firsthalfgameobjects)
{
GameObject obs = Instantiate(Obstacle) as GameObject;
obs.SetActive(false);
Inactivegameobject.Add(obs);
}
}
}

Move a player along Y axis using touch location

I'm trying to move a player when the screen is tapped to where the screen is tapped, but only along the Y axis. I've tried this:
Vector2 touchPosition;
[SerializeField] float speed = 1f;
void Update() {
for (var i = 0; i < Input.touchCount; i++) {
if (Input.GetTouch(i).phase == TouchPhase.Began) {
// assign new position to where finger was pressed
transform.position = new Vector3 (transform.position.x, Input.GetTouch(i).position.y, transform.position.z);
}
}
}
But the player disappears rather than moves. What am I doing wrong?
You need to convert the touch position from Screen to World. This is very easy to do, I've just knocked this quick script together, hopefully it helps:
using UnityEngine;
using System.Collections;
public class TouchSomething : MonoBehaviour
{
public GameObject thingToMove;
public float smooth = 2;
private Vector3 _endPosition;
private Vector3 _startPosition;
private void Awake()
{
_startPosition = thingToMove.transform.position;
}
private void Update()
{
if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
{
_endPosition = HandleTouchInput();
}
else
{
_endPosition = HandleMouseInput();
}
thingToMove.transform.position = Vector3.Lerp(thingToMove.transform.position, new Vector3(_endPosition.x, _endPosition.y, 0), Time.deltaTime * smooth);
}
private Vector3 HandleTouchInput()
{
for (var i = 0; i < Input.touchCount; i++)
{
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
var screenPosition = Input.GetTouch(i).position;
_startPosition = Camera.main.ScreenToWorldPoint(screenPosition);
}
}
return _startPosition;
}
private Vector3 HandleMouseInput()
{
if(Input.GetMouseButtonDown(0))
{
var screenPosition = Input.mousePosition;
_startPosition = Camera.main.ScreenToWorldPoint(screenPosition);
}
return _startPosition;
}
}
This allows you to also test in the editor as well.
I hope this helps.

Categories