I am creating a build in Unity 2019.4.12f1 and need to drag an object with Right Mouse button.
My C# skills are very limited, so far but i try.
This scripts is my attempt to be able to rotate a gameobject by holding right mouse button down and dragging ingame.
But it is wrong.
Can anyone help me correct it?´
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mouseM : MonoBehaviour
{
bool dragging = false;
void Start()
{
if (Input.GetMouseButtonDown(1))
{
dragging = true;
}
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
yourOnMouseDownFunction();
dragging = true;
}
if (Input.GetMouseButtonUp(1))
{
yourOnMouseUpFunction();
dragging = false;
}
if (dragging)
{
yourOnMouseDragFunction();
}
}
}
I understood that You need to Drag Object in 3d World so Here is my Code just create new Script and attach to Object You Want to Drag it
Your Object that You need to Drag it should has a collider
using UnityEngine;
public class DragableObject : MonoBehaviour
{
private Vector3 mOffset;
private float mZCoord;
private void OnMouseDrag()
{
transform.position = GetMouseWorldPos() + mOffset;
}
private void OnMouseDown()
{
mZCoord = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
mOffset = transform.position - GetMouseWorldPos();
}
private Vector3 GetMouseWorldPos()
{
Vector3 mosePoint = Input.mousePosition;
mosePoint.z = mZCoord;
var result = Camera.main.ScreenToWorldPoint(mosePoint);
return result;
}
}
you can try it by adding it to sphere or cube and if you use custom shape you should insure that the collider is in suitable size or has a meshcollier
Demo
EDIT
using UnityEngine;
public class DragableObject : MonoBehaviour
{
private bool isMouseDragging;
private Vector3 screenPosition;
private Vector3 offset;
private GameObject target;
GameObject ReturnClickedObject(out RaycastHit hit)
{
GameObject targetObject = null;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray.origin, ray.direction * 10, out hit))
{
targetObject = hit.collider.gameObject;
}
return targetObject;
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
RaycastHit hitInfo;
target = ReturnClickedObject(out hitInfo);
if (target != null)
{
isMouseDragging = true;
Debug.Log("our target position :" + target.transform.position);
//Here we Convert world position to screen position.
screenPosition = Camera.main.WorldToScreenPoint(target.transform.position);
offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z));
}
}
if (Input.GetMouseButtonUp(1))
{
isMouseDragging = false;
}
if (isMouseDragging)
{
//tracking mouse position.
Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z);
//convert screen position to world position with offset changes.
Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset;
//It will update target gameobject's current postion.
target.transform.position = currentPosition;
}
}
}
You could try the Input.GetMouseButton method, this should return a value depending on if the button is held pressed.
This one works too, if someone needs in the future.
This is for rotate though.
Sorry, i dont know why it wont let me post as code, so i post an image.
enter image description here
Related
I'm trying to get an object to always be "in front" of the player, from a top down perspective. Here's screenshots demonstrating what I'm trying to do.
So as you can see, when the blue capsule (player) picks up the green capsule (item), the item correctly hovers in front of the player (indicated by the z-axis blue arrow), but when the player turns in any other direction, the item doesn't follow, and instead stays in exactly the same position relative to the player.
My player controller script looks as follows:
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float movementSpeed = 10;
private Rigidbody body;
private Vector2 movement;
void Start() {
body = GetComponent<Rigidbody>();
}
void Update() {
movement.x = Input.GetAxis("Horizontal");
movement.y = Input.GetAxis("Vertical");
}
void FixedUpdate() {
body.velocity = new Vector3(movement.x * movementSpeed * Time.deltaTime, 0, movement.y * movementSpeed * Time.deltaTime);
// this is what updates the direction of the blue arrow in the direction of player movement
if(movement.x != 0 || movement.y != 0) {
body.rotation = Quaternion.LookRotation(body.velocity);
}
}
}
And here's my pickup script (where the item's position is supposed to be updated):
using UnityEngine;
public class Pickup : MonoBehaviour {
private GameObject item;
public float carryDistance = 1;
void OnCollisionEnter(Collision collision) {
if(collision.gameObject.CompareTag("Item")) {
item = collision.gameObject;
}
}
void Update() {
if(item) {
item.transform.position = transform.position + new Vector3(0, 0, carryDistance);
}
}
}
So to reiterate my question: How can I update the item's position such that it's always hovering next to the player on the side of the blue arrow?
You can achieve this by using players transform.forward
item.transform.position = transform.position + (transform.forward * carryDistance)
+ (Vector3.up * carryHeight);
Alternatively you can just add empty child gameobject to the player, position it in front of the player and use its transform position and rotation to position the picked up object.
public class Pickup : MonoBehaviour {
public Transform pickupPositionTransform;
private GameObject item;
public float carryDistance = 1;
void OnCollisionEnter(Collision collision) {
if(collision.gameObject.CompareTag("Item")) {
item = collision.gameObject;
}
}
void Update() {
if(item) {
item.transform.position = pickupPositionTransform.position;
item.transform.rotation = pickupPositionTransform.rotation;
}
}
}
I am making a map game in unity. I want to drag the mouse on the map resulting in the player viewing different areas of the map (yes, like Hears of Iron IV). I have tried using the 'onDrag' method but I can not find the proper code for it. Can someone please link some documentation or required code for this method?
Thank you.
If you want to change camera position you can simply do it with this code:
public float dragSpeed = 2;
private Vector3 dragOrigin;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
dragOrigin = Input.mousePosition;
return;
}
if (!Input.GetMouseButton(0)) return;
Vector3 pos = Camera.main.ScreenToViewportPoint(dragOrigin - Input.mousePosition);
Vector3 move = new Vector3(pos.x * dragSpeed, 0, pos.y * dragSpeed);
transform.Translate(move, Space.World);
}
With this, you can start and do other things.
If you want to move the map instead of the camera you can also try :
private bool isDragging;
public void OnMouseDown()
{
isDragging = true;
}
public void OnMouseUp()
{
isDragging = false;
}
void Update()
{
if (isDragging) {
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
transform.Translate(mousePosition);
}
}
this work as Drag and Drop any 2d objects in unity.
the other answer does not work since the map should also move while button is held.. here is the fix
public float dragSpeed = 2;
private Vector3 dragOrigin;
private bool dragStarted = false;
if (Input.GetMouseButtonDown(1))
{
dragOrigin = Input.mousePosition;
dragStarted = true;
}
if (Input.GetMouseButtonUp(1))
{
dragStarted = false;
return;
}
if (dragStarted)
{
Vector3 pos = main_camera.ScreenToViewportPoint(dragOrigin - Input.mousePosition);
Vector3 move = new Vector3(pos.x * dragSpeed, 0, pos.y * dragSpeed);
main_camera.transform.Translate(move, Space.World);
}
this also assumes your camera is pointed downwards or facing north..
I'm starting out with a small shooting game but I have a problem with my character. The arms have to rotate 360º but the body only right or left (depending on where the rotation of the arms by the mouse).
What I got so far is what you see in the video below but I have two big problems and with the help of tutorials.
I was able to rotate and flip my arms but not the body.
Also, when it fires to the right the bullets exit correctly from the firepoint that I created but after the arms flip to the left the bullets (and the weapon fire) are no longer aligned.
Is this approach that I have tried is not the best for this problem?
I appreciate your help.
Game link: https://vimeo.com/310853740
Here my arm rotation script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArmRotation : MonoBehaviour
{
SpriteRenderer spriteRend;
void Awake()
{
spriteRend = GetComponent<SpriteRenderer>();
}
void Update()
{
AimArmAtMouse();
}
void AimArmAtMouse()
{
Vector2 mousePosition = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 armToMouse = mousePosition - (Vector2)transform.position;
float rotationZ = Vector2.SignedAngle(transform.right, armToMouse);
transform.Rotate(0f, 0f, rotationZ);
FlipArm(Vector2.SignedAngle(transform.right, Vector2.right));
}
void FlipArm(float rotation)
{
if (rotation < -90f || rotation > 90f)
{
spriteRend.flipY = true;
}
else
{
spriteRend.flipY = false;
}
}
}
It's because you don't flip the firepoint when you flip the sprite. I re-wrote you script to include a reference to the firepoint. I also added a 'FlipFirePoint' function which gets called by your 'FlipArm' function. It should fix your alignment issue.
using UnityEngine;
public class ArmRotation : MonoBehaviour
{
SpriteRenderer spriteRend;
public Transform firePoint;
void Awake()
{
spriteRend = GetComponent<SpriteRenderer>();
}
void Update()
{
AimArmAtMouse();
}
void AimArmAtMouse()
{
Vector2 mousePosition = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 armToMouse = mousePosition - (Vector2)transform.position;
float rotationZ = Vector2.SignedAngle(transform.right, armToMouse);
transform.Rotate(0f, 0f, rotationZ);
FlipArm(Vector2.SignedAngle(transform.right, Vector2.right));
}
void FlipArm(float rotation)
{
if (rotation < -90f || rotation > 90f)
{
spriteRend.flipY = true;
FlipFirePoint(true);
}
else
{
spriteRend.flipY = false;
FlipFirePoint(false);
}
}
void FlipFirePoint(bool flip)
{
var pos = firePoint.localPosition;
pos.x = Mathf.Abs(pos.x) * (flip ? -1 : 1);
firePoint.localPosition = pos;
}
}
#Sean, I separated the main_body from the arms and made a new script just for body rotation but now it happens to me this:
My test char
The code:
void Update()
{
Flip();
}
void Flip()
{
Vector3 theScale = transform.localScale;
Vector3 pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
float WorldXPos = Camera.main.ScreenToWorldPoint(pos).x;
if (WorldXPos > gameObject.transform.position.x)
{
theScale.x = 1;
transform.localScale = theScale;
}
else
{
theScale.x = -1;
transform.localScale = theScale;
}
}}
Almost there but not yet i need😁
I am trying to move an airplane yoke in the vertical axis. I am using the mouse pointer to move yoke in vertical axis up and down and clamped the value. When I run the script the yoke is positioned some ever and not moving up and down. The yoke is not moving up and down. How to move yoke up and down as shown in the image using below code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace plane
{
public class IP_AirplaneThrottle_Physical : MonoBehaviour
{
#region Variables
public float maxZOffset = -0.5f;
public float sensitivity = 0.001f;
public float smoothSpeed = 8f;
public bool isHitting = false;
public float wantedDelta;
private Vector3 startPos;
private Vector3 wantedPos;
private Vector2 lastMousePosition;
#endregion
#region Builtin Methods
// Use this for initialization
void Start()
{
//Get the lever starting position
startPos = transform.position;
}
// Update is called once per frame
void Update()
{
HandleRaycast();
HandleInteraction();
}
#endregion
#region Custom Methods
void HandleRaycast()
{
//Build a ray so we can see if we are hitting the lever
Ray curRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
//Do our Raycast into the scene
if(Physics.Raycast(curRay, out hit, 1000f))
{
if(hit.transform.GetInstanceID() == this.transform.GetInstanceID())
{
Debug.Log("Hitting the Lever!");
if(Input.GetMouseButtonDown(0))
{
//We are hitting so get the start mouse position
isHitting = true;
lastMousePosition = Input.mousePosition;
print ("123");
}
}
}
//If we let go of the left mouse button then stop everything
if(isHitting && Input.GetMouseButton(0) == false)
{
isHitting = false;
}
}
void HandleInteraction()
{
if(isHitting)
{
//Calculate the delta for Z offset
wantedDelta = (lastMousePosition.y - Input.mousePosition.y) * Time.deltaTime * sensitivity;
startPos.z += wantedDelta;
//make sure we dont go to far
startPos.z = Mathf.Clamp(startPos.z, maxZOffset, 0f);
wantedPos = startPos;
//Get the New Mouse Position every frame while we are holding
lastMousePosition = Input.mousePosition;
}
else
{
//Clear out the Delta value
wantedDelta = 0f;
}
//Move the lever
transform.position = Vector3.Lerp(transform.position, wantedPos, Time.deltaTime * smoothSpeed);
}
#endregion
}
}
using UnityEngine;
using System.Collections;
public class playSound : MonoBehaviour {
private bool destructionHasBegun = false;
public Transform BlueKey;
private void OnTriggerEnter()
{
audio.Play ();
destructionHasBegun = true;
}
private void Update()
{
if(destructionHasBegun)
{
DestroyWhenSoundComplete();
}
}
private void DestroyWhenSoundComplete()
{
if(!audio.isPlaying)
{
Destroy(gameObject);
GameObject textObject = (GameObject)Instantiate(Resources.Load("BlueKey"));
}
}
}
im trying to instantiate the bluekey prefab in a particular position how do i do this? thanks in advance
As per the Instantiate documentation, you can pass in a Vector3 worldspace position as a second parameter.
You'll also need to pass in a Quaternion for its initial rotation as the third parameter; Quaternion.identity is the equivalent of no rotation.
Vector3 newPosition = new Vector3(0, 0, 0);
Quaternion newRotation = Quaternion.identity;
GameObject textObject = (GameObject)Instantiate(Resources.Load("BlueKey"), newPosition, newRotation);