Reputation: 37
I am trying to make a game but when i was coding an aspect it didnt work. So basically, when you enter the trigger, the coffee cup should be in your hands and follow you. I tried to use a coroutine and while loop to do this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrabCoffee : MonoBehaviour
{
// Start is called before the first frame update
public Vector3 pos;
public GameObject coffee;
void Awake()
{
pos = coffee.transform.position;
}
void Start()
{
}
// Update is called once per frame
void Update()
{
}
IEnumerator grabbing()
{
while (true)
{
yield return new WaitForSeconds(0.1f);
pos = new Vector3(pos.x,0.813f,pos.x);
}
}
void OnTriggerEnter(Collider collider)
{
StartCoroutine(grabbing());
}
}
when I collide with this i just go through it and nothing happens
Upvotes: 0
Views: 132
Reputation: 10860
You have your issue because of two reasons:
pos
value is just a position, not the position of the object. You need to assign the new position to the cup's gameObject.transform.position
.new Vector3(pos.x,0.813f,pos.x
) will always have the same value)So, you have at least two options:
collider
variable in the OnTriggerEnter
method to get the target position by using collider.gameObject.transform.position
, store it, and sync your cup gameObject.transform.position
with it in the Update
method)Actually, you should decide what you want to achieve to be able to choose the correct option for your case.
Upvotes: 1
Reputation: 10701
Consider parenting the coffee cup to the hand object. If you don't have a hand object, add an empty game object to the character as child and place it at the hand position.
When you enter the trigger, parent the cup under the hand object and set its position to Vector3.zero
public Transform hand;
public Transform coffee;
void OnTriggerEnter(Collider collider)
{
coffee.SetParent(hand);
coffee.localPosition = Vector3.zero;
}
Upvotes: 1