Ok now i instantiate the prefab with my key, how can i define that the prefab move to the direction of my mouse without using the constant force component in the prefab???
[QUOTE="HiddenMonk, post: 2302354, memberinstâncias aaybe this is what you need http://answers.unity3d.com/questions/119683/instantiate-object-at-mouse-position.html[/QUOTE]
Seems no one get wt i need. I need prefab instantiate at player position (already do it) and i need it to move in direction of mouse cursor… I dont want to instantiate the prefab in mouse position… I want something like diablo skill attack method u usekey 1 to 0 and where u hv the cursor it shot in that direction
Camera.ScreenPointToRay will cast a ray from the near plane of your camera through the specified screen point (in this case, the screen cords of the mouse). This will get you the a world position associated with your mouse, which you can use to determine the facing of your ability.
Ok lets see if i get this to work… my current scrpt is this one, and when i press key “1” the prefab instantiate as it shows in image but dont move, wt i need after it instantiate is that it moves in direction of the place where mouse is in anykind of direction… player simply turn to face direction and instantiate it towards mouse position direction… the instantiate prefab is between line 94 anbd 100
Plz someone guide me here…
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Player : HumanoidControl
{
private static Player instance;
public static Player Instance
{
get
{
if(instance == null)
{
instance = GameObject.FindObjectOfType<Player>();
}
return Player.instance;
}
}
public Image healthBar;
public Text healthtext;
public static Transform opponent;
public static Player player;
bool block;
private Animator anim;
private bool attacking;
private bool running;
private bool sendDamage;
//character base status
public int baseIntellect;
public int baseAgility;
public int baseStrength;
public int baseStamina;
//character modified status with equipment
private int intellect;
private int agility;
private int strength;
private int stamina;
public Text statsText;
public GameObject fireballPrebab;
void Awake()
{
player = this;
anim = GetComponent<Animator>();
}
void Start()
{
curHealth = maxHealth;
SetStatus (0, 0, 0, 0);
}
void Update()
{
healthBar.fillAmount = curHealth / maxHealth;
healthtext.text = "Health: " + curHealth + "/" + maxHealth;
Attack();
AnimatorStateInfo animStateInfo = anim.GetCurrentAnimatorStateInfo(0);
if (animStateInfo.IsName("Attack") && !sendDamage && animStateInfo.normalizedTime > 0.36f)
{
sendDamage = false;
opponent.GetComponent<Enemy>().GetHit(damage);
}
if (Input.GetKeyDown (KeyCode.Alpha1))
{
Vector3 pos = Input.mousePosition;
GameObject go = Instantiate(fireballPrebab, transform.position, transform.rotation) as GameObject;
go.transform.position = Vector3.Lerp (transform.position, pos, 10 * Time.deltaTime);
}
}
public void SetStatus(int intellect, int agility, int strength, int stamina)
{
this.intellect = intellect + baseIntellect;
this.agility = agility + baseAgility;
this.strength = strength + baseStrength;
this.stamina = stamina + baseStamina;
statsText.text = string.Format ("Intellect: {0}\nAgility: {1}\nStrength: {2}\nStamina: {3}", this.intellect, this.agility, this.strength, this.stamina);
}
void OnTriggerStay(Collider other)
{
if (other.name == "HealthRegen")
{
curHealth += 10;
}
if (curHealth > maxHealth)
{
curHealth = maxHealth;
}
}
protected override void Attack()
{
if (Input.GetMouseButtonUp (1))
{
if(opponent != null && Vector3.Distance(opponent.position, transform.position) < attackRange)
{
if(!block)
{
sendDamage = true;
transform.LookAt(opponent);
opponent.GetComponent<Enemy>().GetHit(damage);
attacking = true;
anim.SetTrigger("IsAttacking");
block = true;
Invoke("UnBlock", attackSpeed);
}
if(Vector3.Distance(opponent.position, transform.position) < attackRange && opponent != null)
{
attacking = true;
}
else
{
attacking = false;
}
anim.SetBool ("IsAttacking", attacking);
}
}
}
void UnBlock()
{
block = false;
}
}
This might be what you are looking for.
You would put it on your character.
Click for code
using UnityEngine;
public class ShootAtMouse : MonoBehaviour
{
public GameObject bullet;
public KeyCode shootKey = KeyCode.Mouse0;
public Transform gunHole;
void Update()
{
RotateObjectToMousePosition();
if(CanShoot()) Shoot(TargetMousePosition());
}
void RotateObjectToMousePosition()
{
transform.rotation = TargetMousePosition();
}
bool CanShoot()
{
return Input.GetKeyDown(shootKey);
}
void Shoot(Quaternion targetDirection)
{
//You could also get away with just using your transform.forward if your character is rotated using TargetMousePosition
Instantiate(bullet, gunHole.position, targetDirection);
//Move Bullet... In my case, the bullet has a component on it that moves it.
}
Quaternion TargetMousePosition()
{
Quaternion target = new Quaternion();
Plane playerPlane = new Plane(transform.up, transform.position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float hitDistance = 0f;
if (playerPlane.Raycast(ray, out hitDistance))
{
Vector3 targetPoint = ray.GetPoint(hitDistance);
target = Quaternion.LookRotation(targetPoint - transform.position);
}
return target;
}
}
I got the TargetMousePosition() code from here http://wiki.unity3d.com/index.php?title=LookAtMouse
Many times the answer to what you want is already out there, especially something so basic in terms of game mechanics as this. Usually its faster to just search for other peoples answers than to wait for an answer =)
Hopefully this is what you needed.
I am not sure if you needed help with actually moving the instantiated object, but for that you can just have a component on your bullet prefab that every frame moves the object at a certain speed. Something like the ConstantForce component.
about the move of instantiated prefab i need it jut to move a certain distance in mouse direction because with constanteforce component it follow always predefined direction.
so how how can i apply force in the mouse direction via-code after instantiate prefab?? cuz right now it shot but its not accurate and the player is not lokking at mouse position when it instantiate the prefab
It works perfectly, now i just hv an issue, wt can i do to make my player face the mouse cursor before shoot prefab, cuz if i shot if back to him it get stuck, so i need 1st rotate player to mouse position and then shoot it. Ty
The strange is that it shoots properly but the player dont rotate towards mouse position… am i doing something wrong here??
using UnityEngine;
using System.Collections;
using System.Diagnostics;
using UnityEngine.UI;
public class ShootSkill : MonoBehaviour
{
public GameObject fireballPrefab;
public KeyCode castKey = KeyCode.Alpha1;
public Transform sword;
// Update is called once per frame
void Update ()
{
RotateObjectToMousePosition();
if (CanShoot ())
Shoot (TargetMousePosition ());
}
void RotateObjectToMousePosition()
{
transform.rotation = TargetMousePosition ();
}
bool CanShoot()
{
return Input.GetKeyDown(castKey);
}
void Shoot(Quaternion targetDirection)
{
Instantiate (fireballPrefab, sword.position, targetDirection);
}
Quaternion TargetMousePosition()
{
Quaternion target = new Quaternion();
Plane playerPlane = new Plane (transform.up, transform.position);
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
float hitDistance = 0f;
if (playerPlane.Raycast (ray, out hitDistance))
{
Vector3 targetPoint = ray.GetPoint(hitDistance);
target = Quaternion.LookRotation(targetPoint - transform.position);
}
return target;
}
}
i had to choose sword has object spawn prefab with the gizmo on top of player head so the prefab dont stuck in player when i try shoot back since his not rotating towards mouse direction
Oh I see the issue lol. You have the script on a separate gameobject, so you are not rotating the character. Instead you will need to do something like this.
Create a script just for the TargetMousePosition
(could probably even make it a static method)
Click for TargeMousePosition
using UnityEngine;
public class TargetingMousePosition
{
public Quaternion TargetMousePosition(Transform transform)
{
Quaternion target = new Quaternion();
Plane playerPlane = new Plane(transform.up, transform.position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float hitDistance = 0f;
if (playerPlane.Raycast(ray, out hitDistance))
{
Vector3 targetPoint = ray.GetPoint(hitDistance);
target = Quaternion.LookRotation(targetPoint - transform.position);
}
return target;
}
}
Change your ShootSkill script to this
Click for shootscript
using UnityEngine;
public class ShootAtMouse : MonoBehaviour
{
public GameObject bullet;
public KeyCode shootKey = KeyCode.Mouse0;
public Transform gunHole;
TargetingMousePosition targetingMousePosition = new TargetingMousePosition();
void Update()
{
if(CanShoot()) Shoot(targetingMousePosition.TargetMousePosition(transform));
}
bool CanShoot()
{
return Input.GetKeyDown(shootKey);
}
void Shoot(Quaternion targetDirection)
{
Instantiate(bullet, gunHole.position, targetDirection);
}
}
And then, on your player gameobject, put this script on it.
Click for LookAtMousePosition
using UnityEngine;
public class LookAtMousePosition : MonoBehaviour
{
TargetingMousePosition targetingMousePosition = new TargetingMousePosition();
void Update()
{
transform.rotation = targetingMousePosition.TargetMousePosition(transform);
}
}
Now any object you want to be looking at your mouse, just simply drop that LookAtMousePosition onto it. Keep in mind that the TargetMousePosition method expects you to be using the main camera. You can add a camera parameter to the method to give your own camera or whatever.
Its best to separate things anyways. If you didnt separate it, you wouldnt have such an easy time making any object you desire look at your mouse.
As you code more, you will see the power in separating code so it can be reused ^^
Object oriented programming.
I advise you to keep them separate, but ye, if you had the script on your player, it would have worked with just that one script.
It works but now i hv a problem if im runing left and i put mouse on right player start runs for behind xD instead of runing forward since is always looking mose position
and other thing the TargetingMousePosition script its suposed to be attached to sword too right?
I am not sure as to what you mean. The targetingmouseposition script is a object you can instantiate inside any class you want to use it.
I think its more useful for projectiles than a sword though. (unless if you shoot your sword)
If you want, you could probably use statics to write less code. Though you should be careful with statics.
Static target mouse
using UnityEngine;
public static class Helpers
{
public static Quaternion TargetMousePosition(Transform transform)
{
Quaternion target = new Quaternion();
Plane playerPlane = new Plane(transform.up, transform.position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float hitDistance = 0f;
if (playerPlane.Raycast(ray, out hitDistance))
{
Vector3 targetPoint = ray.GetPoint(hitDistance);
target = Quaternion.LookRotation(targetPoint - transform.position);
}
return target;
}
}
public static class ExtTransform
{
public static void LookAtMouse(this Transform transform)
{
transform.rotation = Helpers.TargetMousePosition(transform);
}
}
You see that I also made an extension method for the transform, so anytime you want your transform to look at the mouse, you could do
using UnityEngine;
public class LookAtMousePosition : MonoBehaviour
{
void Update()
{
transform.LookAtMouse();
}
}
Your shoot code would be this
Shoot code
using UnityEngine;
public class ShootAtMouse : MonoBehaviour
{
public GameObject bullet;
public KeyCode shootKey = KeyCode.Mouse0;
public Transform gunHole;
void Update()
{
if(CanShoot()) Shoot(Helpers.TargetMousePosition(transform));
}
bool CanShoot()
{
return Input.GetKeyDown(shootKey);
}
void Shoot(Quaternion targetDirection)
{
Instantiate(bullet, gunHole.position, targetDirection);
}
}