I have a game where the player clicks on the character and moves them around with the mouse (basically like the launching functionality in Angry Birds). My problem is that the character moves to the mouse’s position if the mouse is clicked anywhere onscreen. I would like it so that the character can be “grabbed” only if the player clicks on the character. The character has a characterController attached. I’m not sure if that makes a difference. Here is my current script:
function Update()
{
if(squirrelActive == false && isLoaded)
{
//get mouse point in world space
var pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos.z = 0; //makes sure Z = 0
//drag squirrel while button pressed
if(drag)
{
transform.position = pos;
}
if(Input.GetMouseButtonDown(0))
{
drag = true;
startPos = pos; //save initial position
}
if(Input.GetMouseButtonUp(0))
{
drag = false;
var dir = startPos - pos; //calculate direction and intensity
moveDirection = dir * launchForce; //launches with force input
squirrelActive = true;//allows squirrel to begin moving freely
}
}
}
I’m pretty new to scripting so any help is greatly appreciated! Thanks!
You can simplify this greatly by using the OnMouseDrag() event that is built into Unity. Here is the reference page: OnMouseDrag
function OnMouseDrag()
{
if(squirrelActive == false && isLoaded)
{
//get mouse point in world space
var pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos.z = 0; //makes sure Z = 0
transform.position = pos;
startPos = pos; //save initial position
var dir = startPos - pos; //calculate direction and intensity
moveDirection = dir * launchForce; //launches with force input
squirrelActive = true;//allows squirrel to begin moving freely
}
}
As long as there is a collider on the object, you can drag it across the screen. Let me know if this works for you.
This is what I do, I use interfaces and enums to determine --what-- I’m clicking. This is only a small example. The full thing is complex and complicated for a new programmer.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface Player
{
INTERFACE clickedObj = GlobalVals.theInterface;
public INTERFACE getClicked(){ return clickedObj; }
}
public class ClickHandler : MonoBehavior
{
public void OnMouseDown()
{
GlobalVals.clickingTerrain = true;
}
public void OnGUI()
{
Player player = new Player();
if(player.getClicked() == INTERFACE.TERRAIN)
{
GUI.Label(new Rect(20,20,100,20,), "Terrain");
}
}
}
public static class GlobalVals
{
public static bool clickingTerrain = false;
public INTERFACE theInterface;
}
enum INTERFACE
{
TERRAIN,
HUD,
GUI,
MENU
}
what about putting a collider on the character with the ‘player’ tag. Then when you click, perform a raycast that checks if what you clicked has the “player” tag.